fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. typedef struct Node {
  5. int data;
  6. struct Node* next;
  7. } Stack;
  8.  
  9. Stack* createNode(int value) {
  10. Stack* head = (Stack*)malloc(sizeof(Stack));
  11. if (head == NULL) {
  12. printf("Memory allocation failed\n");
  13. exit(1);
  14. }
  15. head->data = value;
  16. head->next = NULL;
  17. return head;
  18. }
  19.  
  20. Stack* push(Stack* top, int value) {
  21. Stack* temp = createNode(value);
  22. temp->next = top;
  23. return temp;
  24. }
  25.  
  26. Stack* pop(Stack* top) {
  27. if (top == NULL) {
  28. printf("Stack is Empty\n");
  29. return top;
  30. }
  31. printf("Element popped is %d\n", top->data);
  32. Stack* temp = top;
  33. top = top->next;
  34. free(temp);
  35. return top;
  36. }
  37.  
  38. void peek(Stack* top) {
  39. if (top == NULL) {
  40. printf("Empty\n");
  41. return;
  42. }
  43. printf("%d\n", top->data);
  44. }
  45.  
  46. void traverse(Stack* top) {
  47. if (top == NULL) {
  48. printf("Stack is empty\n");
  49. return;
  50. }
  51. printf("Elements in the stack are:\n");
  52. Stack* ptr = top;
  53. while (ptr != NULL) {
  54. printf("%d\n", ptr->data);
  55. ptr = ptr->next;
  56. }
  57. }
  58.  
  59. int main() {
  60. Stack* top = NULL;
  61. top = push(top, 23);
  62. top = push(top, 24);
  63. top = push(top, 25);
  64.  
  65. traverse(top);
  66.  
  67. top = pop(top);
  68. top = pop(top);
  69.  
  70. peek(top);
  71. traverse(top);
  72.  
  73. return 0;
  74. }
  75.  
Success #stdin #stdout 0.01s 5284KB
stdin
Standard input is empty
stdout
Elements in the stack are:
25
24
23
Element popped is 25
Element popped is 24
23
Elements in the stack are:
23