Write
a C program to implement stack using linked list
DATA STRUCTURE DEFINITION
_____________________________________________________________________
NODE: Data {To store
data in
the Node}
Next {To store link of
the next Node}
Source Code:
- #include <stdio.h>
- #include <stdlib.h>
- struct stack
- {
- int data;
- struct node *next;
- };
- typedef struct stack stack;
- void push(int data);
- int pop();
- void display();
- int top=0,size;
- stack *head=NULL;
- void main()
- {
- int no,ch,e,r;
- printf("\nEnter the size of stack ");
- scanf("%d", &size);
- printf("\n 1 - Push");
- printf("\n 2 - Pop");
- printf("\n 3 - Dipslay");
- printf("\n 0 - Exit");
- do
- {
- printf("\n Enter choice : ");
- scanf("%d", &ch);
- switch (ch)
- {
- case 0:
- break;
- case 1:
- printf("\nEnter data : ");
- scanf("%d", &no);
- push(no);
- break;
- case 2:
- r=pop();
- printf("\n%d popped",r);
- break;
- case 3:
- display();
- break;
- default :
- printf(" Wrong choice, Please enter correct choice ");
- break;
- }
- }while(ch!=0);
- }
- void push(int v)
- {
- if(top<size){
- stack *new_node;
- new_node=(stack*)malloc(sizeof(stack));
- new_node->data=v;
- new_node->next=NULL;
- if(head==NULL)
- head=new_node;
- else
- {
- new_node->next=head;
- head=new_node;
- }
- top++;
- }
- else
- printf("\nStack is full!");
- }
- int pop()
- {
- stack *tmp;
- int v;
- if(top>=1)
- {
- tmp=head;
- head=head->next;
- v=tmp->data;
- free(tmp);
- top--;
- }
- else
- v=-999;
- return v;
- }
- void display()
- {
- stack *p;
- p=head;
- if(p!=NULL)
- {
- printf("\nLinked List\n");
- while(p!=NULL)
- {
- printf("%d ",p->data);
- p=p->next;
- }
- }
- }
Output:
Enter the size of stack 8
1 -
Push
2 -
Pop
3 -
Dipslay
4 -
Exit
Enter choice : 1
Enter data : 33
Enter choice : 1
Enter data : 65
Enter choice : 1
Enter data : 22
Enter choice : 1
Enter data : 77
Enter choice : 2
77 popped
Enter choice : 3
Linked List
22 65 33
Enter choice : 4
0 comments:
Post a Comment