Advertisement
Guest User

Untitled

a guest
Mar 21st, 2019
64
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.96 KB | None | 0 0
  1. struct Node
  2. {
  3.     char *data;
  4.     struct Node *link;
  5. };
  6. struct Node *top;
  7.  
  8. // Utility function to add an element data in the stack
  9. // insert at the beginning
  10. void push(char *data)
  11. {
  12.     // create new node temp and allocate memory
  13.     struct Node *temp;
  14.     temp = (struct Node *)malloc(sizeof(struct Node));
  15.  
  16.     // check if stack (heap) is full. Then inserting an element would
  17.     // lead to stack overflow
  18.     if (!temp)
  19.     {
  20.         printf("\nHeap Overflow");
  21.         abort;
  22.     }
  23.  
  24.     // initialize data into temp data field
  25.     temp->data = data;
  26.  
  27.     // put top pointer reference into temp link
  28.     temp->link = top;
  29.  
  30.     // make temp as top of Stack
  31.     top = temp;
  32. }
  33.  
  34. // Utility function to check if the stack is empty or not
  35. int isEmpty()
  36. {
  37.     return top == NULL;
  38. }
  39.  
  40. // Utility function to return top element in a stack
  41. char *peek()
  42. {
  43.     // check for empty stack
  44.     if (!isEmpty(top))
  45.         return top->data;
  46.     else
  47.         abort();
  48. }
  49.  
  50. // Utility function to pop top element from the stack
  51.  
  52. void pop()
  53. {
  54.     struct Node *temp;
  55.  
  56.     // check for stack underflow
  57.     if (top == NULL)
  58.     {
  59.         printf("\nStack Underflow");
  60.         abort();
  61.     }
  62.     else
  63.     {
  64.         // top assign into temp
  65.         temp = top;
  66.  
  67.         // assign second node to top
  68.         top = top->link;
  69.  
  70.         // destroy connection between first and second
  71.         temp->link = NULL;
  72.  
  73.         // release memory of top node
  74.         free(temp);
  75.     }
  76. }
  77.  
  78. void display() // remove at the beginning
  79. {
  80.     struct Node *temp;
  81.  
  82.     // check for stack underflow
  83.     if (top == NULL)
  84.     {
  85.         printf("\nStack Underflow");
  86.         abort();
  87.     }
  88.     else
  89.     {
  90.         temp = top;
  91.         printf("Stack contains:\n");
  92.         while (temp != NULL)
  93.         {
  94.  
  95.             // print node data
  96.             printf("%s\n", temp->data);
  97.  
  98.             // assign temp link to temp
  99.             temp = temp->link;
  100.         }
  101.     }
  102. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement