fork download
  1. #include<stdio.h>
  2. #include<stdlib.h>
  3. struct node
  4. {
  5. int a;
  6. struct node* next;
  7. };
  8.  
  9. node* top=NULL;
  10.  
  11. void push(int val)
  12. {
  13. //memory allocating for a node
  14. node* tmp=(node*) malloc(sizeof(node));
  15.  
  16. tmp->a=val;
  17. tmp->next=top; //add this new value at the end of the stack
  18.  
  19. //now top of the stack is the new node
  20. top=tmp;
  21. }
  22.  
  23. void pop()
  24. {
  25. node* tmp;
  26.  
  27. if(top==NULL)
  28. printf("Stack is empty");
  29. else
  30. {
  31. printf("popped element %d\n",top->a);
  32. tmp=top;
  33. //top is replaced to the next node
  34. top=top->next;
  35.  
  36. //top node is deleted from the memory
  37. free(tmp);
  38. }
  39. }
  40.  
  41. void printlist(node* link)
  42. {
  43. //recursively printing the list to find the actual order of the values
  44. if(link!=NULL)
  45. {
  46. printlist(link->next);
  47. printf("%d ",link->a);
  48. }
  49. }
  50.  
  51. int main()
  52. {
  53. int num,val;
  54. bool getout=false;
  55.  
  56. while(true)
  57. {
  58. printf("Enter your choice:\n");
  59. printf("1. Push\n2. Pop\n3. Exit\n");
  60. scanf("%d",&num);
  61.  
  62. switch(num)
  63. {
  64. case 1:
  65. scanf("%d",&val);
  66.  
  67. push(val);
  68.  
  69. printf("now the list is: ");
  70. printlist(top);
  71. puts("");
  72. break;
  73. case 2:
  74. pop();
  75.  
  76. printf("now the list is: ");
  77. printlist(top);
  78. puts("");
  79. break;
  80. case 3:
  81. getout=true;
  82. break;
  83. }
  84.  
  85. if(getout==true)
  86. break;
  87. }
  88.  
  89. return 0;
  90. }
  91.  
Success #stdin #stdout 0s 3032KB
stdin
1 
10 
1 
20 
2 
2 
2 
3
stdout
Enter your choice:
1. Push
2. Pop
3. Exit
now the list is: 10 
Enter your choice:
1. Push
2. Pop
3. Exit
now the list is: 10 20 
Enter your choice:
1. Push
2. Pop
3. Exit
popped element 20
now the list is: 10 
Enter your choice:
1. Push
2. Pop
3. Exit
popped element 10
now the list is: 
Enter your choice:
1. Push
2. Pop
3. Exit
Stack is emptynow the list is: 
Enter your choice:
1. Push
2. Pop
3. Exit