Implement the stack using a linked list. Use the following class definition for
ID: 3629997 • Letter: I
Question
Implement the stack using a linked list. Use the following class definition for the stack and use the given main function to test your implementation.#include <iostream>
typedef int StackElement;
struct node
{
StackElement data;
node * next;
};
class Stack
{
public:
Stack(); // create an empty stack
bool empty(); //return true if stack is empty, otherwise return false
void push(StackElement x); //add a new value to the top of the stack
bool Top(StackElement & x); //retrieves the data that is at the top of the stack
void pop(); //removes the value at the top of the stack
void display(); //displays the data stored in the stack
private:
node * mytop; //pointer to the top of the stack
};
int main()
{
Stack S;
// insert values 10, 20, 30, 40 and 50 onto the stack
for(int x = 1; x<=5; x++){
int n = x*10;
S.push(n);
}
//Display the content of the stack to the screen
S.display();
cout<<endl<<endl;
//Remove and display each value on the stack
while (!S.empty())
{ int x;
S.Top(x);
cout<<endl;
cout<<”Popping --- “ <<x<<endl;
S.pop();
S.display();
}
if (S.empty())
cout<< “Stack is empty.”<<endl;
}
Explanation / Answer
#include <iostream.h>
#include <conio.h>
class Stack //Global declaration
{
int ele,pos;
Stack *top,*next,*fresh,*temp;
public:
Stack()
{
top=NULL;
pos=0;
}
void menu()
{
cout<<"STACK OPERATIONS"<<endl;
cout<<"----------------"<<endl;
cout<<"1.PUSH"<<endl;
cout<<"2.POP"<<endl;
cout<<"3.DISPLAY"<<endl;
cout<<"4.EXIT"<<endl;
}
void push()
{
fresh=new Stack();
cout<<"Enter the element "<<endl;
cin>>fresh->ele;
fresh->next=top;
top=fresh;
}
void pop()
{
if(top==NULL)
cout<<"Deletion is not possible.Stack is empty"<<endl;
else
{
cout<<"Popped element is:"<<top->ele<<endl;
temp=top;
top=top->next;
delete temp;
}
}
void display()
{
if(top==NULL)
cout<<"Stack is empty"<<endl;
else
{
cout<<"The elements in the stack are:"<<endl;
temp=top;
while(temp!=NULL)
{
cout<<temp->ele<<endl;
temp=temp->next;
}
}
}
};