fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. typedef struct node {
  5.  
  6. int val;
  7. struct node* next;
  8.  
  9. } STACK;
  10.  
  11. STACK* push (STACK* stack, int val);
  12. STACK* pop (STACK** stack);
  13. void printStack (STACK* stack);
  14.  
  15. int main (void) {
  16.  
  17. STACK* stack = NULL;
  18.  
  19. printStack (stack);
  20. stack = push (stack, 5);
  21. stack = push (stack, 4);
  22. stack = push (stack, 3);
  23. printStack (stack);
  24. pop (&stack);
  25. pop (&stack);
  26. printStack (stack);
  27. stack = push (stack, 2);
  28. printStack (stack);
  29. pop (&stack);
  30. printStack (stack);
  31. pop (&stack);
  32. printStack (stack);
  33. stack = push (stack, 6);
  34. printStack (stack);
  35. pop (&stack);
  36. printStack (stack);
  37.  
  38. return 0;
  39.  
  40. }
  41.  
  42.  
  43. STACK* push (STACK* stack, int val) {
  44.  
  45. STACK* pNew = malloc (sizeof (STACK));
  46. pNew->val = val;
  47. pNew->next = stack;
  48. stack = pNew;
  49.  
  50. return stack;
  51.  
  52. }
  53.  
  54.  
  55. STACK* pop (STACK** stack) {
  56.  
  57. STACK* temp = *stack;
  58.  
  59. if (temp) {
  60.  
  61. *stack = temp->next;
  62. temp->next = NULL;
  63.  
  64. }
  65.  
  66. return temp;
  67.  
  68. }
  69.  
  70.  
  71. void printStack (STACK* stack) {
  72.  
  73. if (!stack) {
  74.  
  75. printf ("Stack is empty\n");
  76. return;
  77. }
  78.  
  79. printf ("Stack has:");
  80.  
  81. while (stack) {
  82.  
  83. printf (" %d", stack->val);
  84. stack = stack->next;
  85.  
  86. }
  87.  
  88. putchar ('\n');
  89.  
  90. return;
  91.  
  92. }
  93.  
Success #stdin #stdout 0s 2424KB
stdin
Standard input is empty
stdout
Stack is empty
Stack has: 3 4 5
Stack has: 5
Stack has: 2 5
Stack has: 5
Stack is empty
Stack has: 6
Stack is empty