Stack Using Linked-List
Algorithm : Stack Using Linked-List Let us consider a linked-list pointed by header node.We have to Implement Stack operations(i.e push and pop)using this linked list. Push(header,item) { t=getnode() //getnode() is a function which creates a new node t->data=item and returns the address of the node if(header->link=NULL) //checks if the linked-list is empty header->link=t else { t->link=header->link //t points to the 1st node of the list header->link=t //header points to t,hence t becomes the } 1st node of the list } Pop(header) { if(header->link=NULL) //checks if the linked list is empty { Print "nStack underflow" return } else { x=header->link header->link=x->link //the 1st node is deleted return x->data } } Show(header) { trav=header->link if(trav=NULL) print "Stack empty" else { while(trav≠NULL) //until the list becomes empty { Print “trav->data” trav=trav->link //trav moves to next node } } } #include>stdio.h> #include>conio.h> #include>stdlib.h> struct node { int data; struct node *link; }; struct node *header; struct node * getnode() { struct node *t; int item; t=(struct node *)malloc(sizeof(struct node)); printf("\nEnter your item:"); scanf("%d",&item); t->data=item; t->link=NULL; return t; } void show() { struct node *trav; trav=header->link; if(trav==NULL) printf("\nStack empty."); else { printf("\nSTACK elements are:\n\n"); while(trav!=NULL) { printf(" %d",trav->data); trav=trav->link; } } printf("\n"); } void push() { struct node *t; t=getnode(); if(header->link==NULL) { header->link=t; } else { t->link=header->link; header->link=t; } } int pop() { struct node *x; if(header->link==NULL) { printf("\nStack underflow.\n"); } else { x=header->link; header->link=x->link; return x->data; } } void main() { int ch,item; clrscr(); while(1) { printf("\nSTACK operations:"); printf("\n1.Push 2.Pop 3.Show 4.Exit"); printf("\nEnter your choice:"); scanf("%d",&ch); switch(ch) { case 1: push(); break; case 2: item=pop(); break; case 3: show(); break; case 4: exit(0); } } getch(); } OUTPUT : STACK operations: 1.Push 2.Pop 3.Show 4.Exit Enter your choice:1 Enter your item:11 STACK operations: 1.Push 2.Pop 3.Show 4.Exit Enter your choice:1 Enter your item:22 STACK operations: 1.Push 2.Pop 3.Show 4.Exit Enter your choice:1 Enter your item:33 STACK operations: 1.Push 2.Pop 3.Show 4.Exit Enter your choice:1 Enter your item:44 STACK operations: 1.Push 2.Pop 3.Show 4.Exit Enter your choice:3 STACK elements are: 44 33 22 11 STACK operations: 1.Push 2.Pop 3.Show 4.Exit Enter your choice:2 STACK operations: 1.Push 2.Pop 3.Show 4.Exit Enter your choice:2 STACK operations: 1.Push 2.Pop 3.Show 4.Exit Enter your choice:2 STACK operations: 1.Push 2.Pop 3.Show 4.Exit Enter your choice:3 STACK elements are: 11 STACK operations: 1.Push 2.Pop 3.Show 4.Exit Enter your choice:2 STACK operations: 1.Push 2.Pop 3.Show 4.Exit Enter your choice:2 Stack underflow.
Tags:
Stack & Linked List
0 comments