Advertisement
Guest User

STACK IMPLEMENTATION

a guest
Oct 18th, 2018
97
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.45 KB | None | 0 0
  1.  
  2. // C program for linked list implementation of stack
  3. #include <stdio.h>
  4. #include <stdlib.h>
  5. #include <limits.h>
  6.  
  7. // A structure to represent a stack
  8. struct StackNode
  9. {
  10.     int data;
  11.     struct StackNode* next;
  12. };
  13.  
  14. struct StackNode* newNode(int data)
  15. {
  16.     struct StackNode* stackNode =
  17.               (struct StackNode*) malloc(sizeof(struct StackNode));
  18.     stackNode->data = data;
  19.     stackNode->next = NULL;
  20.     return stackNode;
  21. }
  22.  
  23. int isEmpty(struct StackNode *root)
  24. {
  25.     return !root;
  26. }
  27.  
  28. void push(struct StackNode** root, int data)
  29. {
  30.     struct StackNode* stackNode = newNode(data);
  31.     stackNode->next = *root;
  32.     *root = stackNode;
  33.     printf("%d pushed to stack\n", data);
  34. }
  35.  
  36. int pop(struct StackNode** root)
  37. {
  38.     if (isEmpty(*root))
  39.         return INT_MIN;
  40.     struct StackNode* temp = *root;
  41.     *root = (*root)->next;
  42.     int popped = temp->data;
  43.     free(temp);
  44.  
  45.     return popped;
  46. }
  47.  
  48. int peek(struct StackNode* root)
  49. {
  50.     if (isEmpty(root))
  51.         return INT_MIN;
  52.     return root->data;
  53. }
  54.  
  55. int main()
  56. {
  57.     struct StackNode* root = NULL;
  58.  
  59.     push(&root, 10);
  60.     push(&root, 20);
  61.     push(&root, 30);
  62.  
  63.     printf("%d popped from stack\n", pop(&root));
  64.  
  65.     printf("Top element is %d\n", peek(root));
  66.  
  67.      // Free memory
  68.     struct StackNode *ptr = root;
  69.     while (ptr != NULL)
  70.     {
  71.         struct StackNode *next = ptr->next;
  72.         free(ptr);
  73.         ptr = next;
  74.     }
  75.  
  76.     return 0;
  77. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement