Advertisement
Shailrshah

Stack using Linked List

Aug 17th, 2013
161
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.57 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. struct stack{
  4.     int data;
  5.     struct stack *bottom;
  6. }*top = NULL;
  7. void push(int value){//value is to be inserted in the stack
  8.     struct stack *newNode = (struct stack *)malloc(sizeof(struct stack));//memory for new node
  9.     newNode->data = value; newNode->bottom = NULL;//assign values to new node
  10.     if(top) newNode->bottom = top;//if stack is not empty, newNode's bottom points where top points
  11.     top = newNode;//top points to the new node
  12. }
  13. void pop(){
  14.     struct stack *target = top;//target is the top-most element in the stack
  15.     top = top->bottom;//top points to the bottom element in the stack
  16.     free(target);//target is freed as it's no longer needed
  17. }
  18. void display(){
  19.     if(!help)printf("\nStack is Empty!\n");
  20.     else{
  21.         struct stack *help = top;
  22.         while(help){
  23.             printf("\t%d\n",help->data);
  24.             help = help->bottom;
  25.         }
  26.     }
  27. }
  28. int main()
  29. {
  30.     int n;
  31.     while(1){
  32.         display();
  33.         printf(" \n1. Push 2. Pop 3. Exit\n");
  34.         printf(" \nChoose Option: ");
  35.         scanf("%d", &n);
  36.         switch(n){
  37.         case 1:
  38.             printf("\nEnter an integer to push onto the Stack: ");
  39.             scanf("%d",&n);
  40.             push(n);
  41.             break;  
  42.         case 2:  
  43.             if(top)   pop();
  44.             break;            
  45.         case 3:
  46.             printf("\nMore programs @ pastebin.com/u/shailrshah\n");
  47.             return 0;              
  48.         default:
  49.             printf("\nInput Error. Try again.");              
  50.     }
  51.   }
  52. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement