ALGORITHM:
- Create a class Node.
- create a next pointer
- create a previous pointer
- create a variable to store data
- Create a class Stack.
- Create a node pointer top, which will represent the top element of our stack.
- Create a push() function.
- Create a temporary pointer of node class
- If top is equal to NULL
- Assign top to a new Node
- Assign the temporary pointer to top
- Assign next pointer of top to NULL
- Assign previous pointer of top to NULL
- Else
- Assign next pointer of top to new Node
- Assign top to next pointer of top
- Assign previous pointer of Top to temporary
- Assign temporary to top
- Assign next pointer of top to NULL
- Create a pop() function.
- Create a temporary pointer of Node class and assign it to top
- If temporary node is equal to NULL
- Print Stack is empty
- Else
- Assign top to previous node of top
- return data of temporary Node
- Create a top() function.
- Create a temporary pointer of Node class and assign it to top
- If temporary node is equal to NULL
- Print Stack is empty
- Else
- return data of temporary Node
- Create a display() function. //OPTIONAL
- Create a temporary pointer of Node class and assign it to top
- If temporary node is equal to NULL
- Print Stack is empty
- Else
- Loop until temporary node is not equal to NULL
- Print data of temporary Node
- Assign temporary Node to previous node of temporary node
CODE:
#include<iostream>class Node{
public:
char data;
Node *pNext;
Node *pPrev;
Node(char );
};
class Stack{
public:
Node *pTop;
Stack();
void push(char );
char pop();
char top();
void display();
};
int main(){
Stack s;
s.push('1');
s.push('2');
s.push('3');
std::cout << "\nTop: " << s.top();
s.display();
std::cout << "\nPopped: " << s.pop();
std::cout << "\nPopped: " << s.pop();
std::cout << "\nTop: " << s.top();
return 0;
}
//NODE
Node::Node(char d){
data = d;
pNext = NULL;
pPrev = NULL;
}
//STACK
Stack::Stack(){
pTop = NULL;
}
void Stack::push(char data){
Node *pTemp;
if(pTop == NULL){
pTop = new Node(data);
pTemp = pTop;
pTop->pNext = NULL;
pTop->pPrev = NULL;
} else {
pTop->pNext = new Node(data);
pTop = pTop->pNext;
pTop->pPrev = pTemp;
pTemp = pTop;
pTop->pNext = NULL;
}
}
void Stack::display(){
Node *pTemp = pTop;
if(pTemp == NULL){
std::cout << "\nStack is Empty";
} else {
while(pTemp != NULL){
std::cout << "\n" << pTemp->data;
pTemp = pTemp->pPrev;
}
}
}
char Stack::pop(){
Node *pTemp = pTop;
if(pTemp == NULL){
std::cout << "\nStack is Empty";
} else {
pTop = pTop->pPrev;
return pTemp->data;
}
}
char Stack::top(){
Node *pTemp = pTop;
if(pTemp == NULL){
std::cout << "\nStack is Empty";
} else {
return pTemp->data;
}
}