C++ Help! implementation of Node based Stack data structure? #include using name
ID: 3761926 • Letter: C
Question
C++ Help! implementation of Node based Stack data structure?
#include
using namespace std;
class Stack;
class Node{
private:
Node(char, Node*);
char data;
Node* next;
friend class Stack;
friend ostream& operator<<(ostream&, const Stack&);
};
class Stack{
public:
Stack(int = 0);
Stack(const Stack&);
~Stack();
Stack& operator=(const Stack&);
bool push(char);
bool pop(char&);
bool empty() const;
bool full() const;
bool clear();
bool operator==(const Stack&) const;
friend ostream& operator<<(ostream&, const Stack&);
private:
Node* top;
};
Explanation / Answer
#include <bits/stdc++.h>
using namespace std;
class Node{
private:
char data;
Node* next;
Node(char d,Node* n);
};
Node::Node(char d,Node* n){
data = d;
next = n;
}
class Stack{
public:
Stack(int n);
Stack(const Stack&);
~Stack();
Stack& operator=(const Stack&);
bool push(char ch);
bool pop();
bool empty();
bool full();
bool clear();
bool operator==(const Stack&) const;
private:
Node* top;
int size;
int capacity;
};
Stack::Stack(int n){
capacity = n;
size = 0;
}
Stack::~Stack(){}
bool Stack::push(char ch){
if (size == capacity)
return false;
Node *n = new Node(ch);
n->next = top;
top = n;
size += 1;
return true;
}
bool Stack::pop(){
if (top == NULL)
return false;
top = top->next;
}
bool Stack::empty() const{
if (top == NULL)
return true;
return false;
}
bool Stack::full() const{
if (size == capacity)
return true;
return false;
}
bool Stack::clear(){
top = NULL;
size = 0;
return true;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.