Advertisement
BlankOD

Untitled

Mar 12th, 2022
1,472
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.34 KB | None | 0 0
  1. #include<stdio.h>
  2. #include<stdlib.h>
  3. // Struct to hold the data and the pointer to the next element.
  4. struct element{
  5.     char data;
  6.     struct element* next;
  7. };
  8. // Append the new element to the start of the stack
  9. void push(char data, struct element** stack){
  10.     struct element* Element = (struct element*)malloc(sizeof(struct element));
  11.     Element -> data = data;
  12.     Element -> next = *stack;  
  13.     (*stack) = Element;  
  14. }
  15. // Remove element from the top of the stack
  16. void pop(struct element** stack){
  17.     if(*stack != NULL){
  18.         printf("Element popped: %c\n",(*stack) -> data);
  19.         struct element* tempPtr = *stack;
  20.         *stack = (*stack) -> next;
  21.         free(tempPtr);
  22.     }
  23.     else{
  24.         printf("The stack is empty.\n");
  25.     }
  26. }
  27. // Display the element at the top of the stack
  28. void top(struct element* stack){
  29.     if(stack != NULL){
  30.     printf("Element on top: %c\n", stack -> data);
  31.     }
  32.     else{
  33.         printf("The stack is empty.\n");
  34.     }
  35. }
  36. int main() {
  37.     struct element* root = (struct element*)malloc(sizeof(struct element));
  38.     root -> data = 'a';
  39.     root -> next = NULL;
  40.     top(root);
  41.     push('b',&root);
  42.     top(root);
  43.     push('c',&root);
  44.     top(root);
  45.     pop(&root);
  46.     top(root);
  47.     pop(&root);
  48.     top(root);
  49.     pop(&root);
  50.     top(root);
  51.     pop(&root);
  52.     return 0;
  53. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement