Here, I am present the stack through linked list
- stack linked-list
#include<stdio.h> #include<stdlib.h> int count=0; struct node { int data; struct node *next; }*first=NULL,*temp=NULL,*newnode=NULL,*t=NULL; struct node* createnode() { int x; temp=(struct node*)malloc(sizeof(struct node)); printf("\nEnter value:"); scanf("%d",&x); if(temp!=NULL) { temp->data=x; temp->next=NULL; return temp; } else { printf("\nMemory not allocated"); return 0; } } void display() { if(first!=NULL) { for(temp=first;temp->next!=NULL;temp=temp->next) printf("%d->",temp->data); printf("%d->NULL",temp->data); } else printf("\nstack is empty"); } void push() { newnode=createnode(); count++; if(first==NULL) { first=newnode; } else { for(temp=first;temp->next!=NULL;temp=temp->next); temp->next=newnode; newnode->next=NULL; } display(); } void pop() { if(first==NULL) printf("\nUNDERFLOW"); else { for(temp=first;temp->next!=NULL;temp=temp->next); t=temp->next; temp->next=NULL; free(t); count--; } display(); } void peep() { int m,i=1; printf("\nEnter position to peep"); scanf("%d",&m); if(m>count) printf("\nEnter valid position"); else { for(temp=first;i<=count-m;i++,temp=temp->next); printf("\nValue=%d",temp->data); } } main() { int choice; while(1) { printf("\nMENU\n1.PUSH\n2.POP\n3.PEEP\n4.DISPLAY\n5.EXIT"); printf("\nEnter choice:"); scanf("%d",&choice); switch(choice) { case 1: push(); break; case 2: pop(); break; case 3: peep(); break; case 4: display(); break; case 5: exit(0); default : printf("\nEnter valid choice."); } } } |
Happy coding😆😁
إرسال تعليق
Hii