Tuesday, October 14, 2008

6.3 STACK USING SINGLE LINKED LIST

Program Definition
Insert a set of integers into the stack and delete these integers by stack using linked lists
Algorithm:
Algorithm for push operation
//type is the type of data
Node = record
{
Type=data; node *link;
}
1. Algorithm add(item)
2. {
3. //get a newnode
4. temp:=newnode;
5. if(temp!=0)then
6. {
7. (temp->data):=item;(temp->link):=top;
8. top:=temp;
9. return true;
10. }
11. else
12. {
13. write (“out of space!”);
14. return false;
15. }
16. }
Algorithm for pop operation
1. Algorithm delete(item)
2. {
3. if(top=0)then
4. {
5. write(“stack is empty”);
6. return false;
7. }
8. else
9. {
10. item:=(top->data);temp:=top;
11. top:=(top->link);
12. delete temp;
13. return true;
14. }
15. }

Stack using linked list output:

1.push 2.pop 3.display 4.exit
enter your chioce:1
enter element into the stack:9

1.push 2.pop 3.display 4.exit
enter your chioce:1
enter element into the stack:8

1.push 2.pop 3.display 4.exit
enter your chioce:1
enter element into the stack:7

1.push 2.pop 3.display 4.exit
enter your chioce:2
element deleted from stack is:7

1.push 2.pop 3.display 4.exit
enter your chioce:3
elements present in the stack are
8
9
1.push 2.pop 3.display 4.exit
enter your chioce:2
element deleted from stack is:8

1.push 2.pop 3.display 4.exit
enter your chioce:2
element deleted from stack is:9
1.push 2.pop 3.display 4.exit
enter your chioce:3
stack is empty
1.push 2.pop 3.display 4.exit
enter your choice: 4


CODE
#include
#include
#include
#include
class sll
{
private:
int element;
struct node
{
int value;
node *next;
};
typedef struct node nodeptr;
nodeptr *top;
public:
sll()
{
top=NULL;
}
void insert();
void delelement();
void display();
};
void sll::insert()
{
nodeptr *temp;
temp=new nodeptr;
cout<<"enter element into the stack:";
cin>>element;
temp->value=element;
temp->next=NULL;
if(top==NULL)
{
top=temp;
top->next=NULL;
}
else
{
temp->next=top;
top=temp;
}
}
void sll::delelement()
{
nodeptr *temp;
temp=top;
if(top==NULL)
cout<<"stack is empty\n";
else
{
top=top->next;
cout<<"element deleted from stack is:"<value< delete temp;
}
}
void sll::display()
{
nodeptr *temp;
if(top==NULL)
cout<<"stack is empty\n";
else
{
cout<<"elements present in the stack are\n";
for(temp=top;temp!=NULL;temp=temp->next)
{
cout<value<<"\n";
}
}
}
void main()
{
int chioce;
sll s;
clrscr();
while(1)
{
cout<<"\n1.push 2.pop 3.display 4.exit"<<"\n";
cout<<"enter your chioce:";
cin>>chioce;
switch(chioce)
{
case 1: s.insert();
break;
case 2: s.delelement();
break;
case 3: s.display();
break;
case 4:exit(0);
}
}
}

No comments: