Stack Implemented as Linked List
In my previous post, i presented you the C-code of a stack implemented as an array. Now the same stack can be implemented with the help of a linked list. The major advantage is that there is no stack FULL condition when implemented as a linked list as compared to implementation with array.
Below is the working C code of a STACK implemented with the help of linked list.
Below is the working C code of a STACK implemented with the help of linked list.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 | // Stack implementation as a link list. #include<stdio.h> #include<stdlib.h> struct Node { int data; struct Node *next; }*top=NULL; void push(int query) { struct Node *node=(struct Node *) malloc(sizeof(struct Node)); // type casting in malloc is not required in C, even then just to make sure things run OK. node->data=query; node->next=top; top=node; } int pop() { int n=top->data; top=top->next; return n; } void display() { struct Node *temp=top; printf("Elements of the STACK, from the top are: "); for(;temp!=NULL;temp=temp->next) printf("%d ",temp->data); printf("\n"); } int main() { int choice,query; while(1) { printf("Enter the operation for the stack.\n"); printf("1. PUSH\n"); printf("2. POP\n"); printf("3. DISPLAY\n"); printf("4. EXIt\n"); scanf("%d",&choice); switch(choice) { case 1: printf("Enter the element to be pushed: \n"); scanf("%d",&query); push(query); printf("The node with data %d is pushed in the STACK. :)\n",query); break; case 2: if(top==NULL) { printf("Empty STACK. :(\n"); break; } printf("Element %d poped from the STACK. :)\n",pop()); break; case 3: if(top==NULL) { printf("Empty STACK. :(\n"); break; } display(); break; case 4: return 0; } } } // There is no stack full condition in implementation of a stack as a linked list. |