Code for implementing Stack using Linked List
For learning c code in more advanced form, students are advised to practice few codes related to pointer, dynamic memory allocation. For learning pointer, dynamic memory allocation, linked list, you should go through this code. This is Code for implementing Stack using Linked List.
In C code practice, this Code for implementing Stack using Linked List logic plays a very important role. So I have designed this code as easy as possible for the students. They will be able to understand each and every step very easily.
Before going for this type of program a student should go through basics of pointer, dynamic memory allocation etc. So that they can easily go through each step with self explanation mode.
For more code click here. For video tutorial on several topics click here
#include<stdio.h> #include<conio.h> typedef struct StackLinked { int val; struct StackLinked *next; }sl; sl *push(sl *,int); int pop(sl **); int peek(sl *); int isempty(sl *); void disp(sl *); void main() { sl *top=NULL; int ch,v; while(1) { printf("\n\n1) Push\n\n2) Pop\n\n3) Peek\n\n4) Display\n\n5) Exit"); printf("\n Enter your choice :"); scanf("%d",&ch); switch(ch) { case 1: printf("\n Enter the number you want to push : "); scanf("%d",&v); top=push(top,v); break; case 2: if(!isempty(top)) { printf("\n\nYou have popped %d",pop(&top)); } else printf("\n\nNothing to pop"); break; case 3: if(!isempty(top)) { printf("\n\nTop most value is %d",peek(top)); } else printf("\nNothing in the stack"); break; case 4: if(!isempty(top)) { printf("\n\nValues in the stack are: "); disp(top); } else printf("\n\nNothing to display"); break; case 5: exit(0); default: printf("\n\nWrong choice "); } } } sl *push(sl *h,int p) { sl *temp; temp=(sl*) malloc(sizeof(sl)); temp->val=p; temp->next=h; h=temp; return h; } int pop(sl **h) { int v; v=(*h)->val; *h=(*h)->next; return v; } int peek(sl *h) { return h->val; } int isempty(sl *h) { if(h==NULL) return 1; else return 0; } void disp(sl *h) { sl *t; t=h; while(t!=NULL) { printf("\n|%3d|",t->val); t=t->next; } }