Ex - No.6 Implementation of Stacks As Linked Lists 22.1.'10 Aim
Ex - No.6 Implementation of Stacks As Linked Lists 22.1.'10 Aim
22.1.’10
AIM:
To write a C++ program to implement stacks using linked lists and to perform the basic
operations .
ALGORITHM:
STEP 1: Start.
STEP 2: A structure is created to implement the nodes in the linked list which contains a ‘data’
part and a link to the next node.
STEP 3: The PUSH function adds an element to the top of the stack.
STEP 4: The POP function deletes an element from the top of the stack.
STEP 5: Stop.
CODING:
#include<iostream.h>
#include<conio.h>
class stack
private:
struct node
int d;
node *link;
}*top;
public:
stack();
int pop();
};
stack::stack()
top=NULL;
void stack::push(int i)
{
node *temp;
temp=new node;
if(temp==NULL)cout<<"Stack is full";
temp->data=i;
temp->link=top;
top=temp;
int stack::pop()
if(top==NULL)
cout<<"Stack is empty";
return NULL;
node *temp;
int i;
temp=top;
i=temp->d;
top=top->link;
delete temp;
return i;
}
void main()
clrscr();
int a,ch,c=3;
stack s;
s.stack();
while(c==3)
cin>>ch;
switch(ch)
case 1:
cin>>a;
s.push(a);
break;
case 2:
int v=s.pop();
cout<<"\n The popped element is "<<v;
break;
cin>>c;
getch();
}
OUTPUT:
1.PUSH
2.POP
Enter 3 to continue
1.PUSH
2.POP
Enter 3 to continue
1.PUSH
2.POP
Enter 3 to continue
1.PUSH
2.POP
Enter 3 to continue
4
RESULT:
Thus a C++ program was executed successfully to implement stacks using linked lists.