The ones who are crazy enough to think they can change the world are the ones who do.- Steve Jobs
When a stack is created using array, we will come across a set of problems.
If the elements in a stack is in very less amount as compare to the size of a stack, then more amount of memory spaces will remain useless.
If we are processing the unknown amount of data to pushed into a stack. Then, definitely we will come across the shortage of memory spaces.
The above two problems are rectified by using linked list instead of using array.
Here is the program to demonstrate Linked stack.
#include <stdio.h> #include <malloc.h> struct stack{ int data; struct stack *next; }; struct stack *top = NULL; struct stack *push(struct stack*, int); struct stack *display(struct stack *); struct stack *pop(struct stack *); int peek(struct stack *); int main(){ int val,option; do{ printf("\n1. Push"); printf("\n2. POP"); printf("\n3. PEEK"); printf("\n4. DISPLAY"); printf("\n5. EXIT"); printf("\n Enter your option : "); scanf("%d",&option); switch(option) { case 1: printf("\n Enter the number to be pushed on stack : "); scanf("%d",&val); top = push(top,val); break; case 2: top = pop(top); break; case 3: val = peek(top); if(val != -1) printf("\n The value at the top of stack is : %d",val); else printf("\nSTACK IS EMPTY"); break; case 4: top = display(top); break; } }while(option != 5); return 0; } struct stack *push(struct stack *top, int val) { struct stack *ptr; ptr = (struct stack*)malloc(sizeof(struct stack)); ptr -> data= val; if(top == NULL) { ptr -> next = NULL; top= ptr; } else{ ptr -> next = NULL; top = ptr; } return top; } struct stack *display(struct stack *top) { struct stack *ptr; ptr = top; if(top == NULL) printf("\nSTACK IS EMPTY"); else{ while(ptr != NULL) { printf("\n%d",ptr -> data); ptr = ptr -> next; } } return top; } struct stack *pop(struct stack *top){ struct stack *ptr; ptr=top; if(top == NULL) printf("\nSTACK UNDERFLOW"); else{ top=top -> next; printf("\n The value being deleted is : %d",ptr -> data); free(ptr); } return top; } int peek(struct stack *top) { if(top == NULL) return -1; else return top -> data; }
1. PUSH 2. POP 3. PEEK 4. DISPLAY 5. EXIT Enter your option : 1 Enter the number to be pushed on stack : 1 1. PUSH 2. POP 3. PEEK 4. DISPLAY 5. EXIT Enter your option : 2 The value being deleted is : 1 1. PUSH 2. POP 3. PEEK 4. DISPLAY 5. EXIT Enter your option : 4 STACK IS EMPTY 1. PUSH 2. POP 3. PEEK 4. DISPLAY 5. EXIT Enter your option : 5
We may make mistakes(spelling, program bug, typing mistake and etc.), So we have this container to collect mistakes. We highly respect your findings.
© Copyright 2019