tampurus

2.21 Dynamic stack CPP

May 31st, 2022
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.75 KB | None | 0 0
  1. #include<iostream>
  2. #include<stdlib.h>
  3. int S_size = 0; // dynamic size of stack
  4. struct Node{
  5.     int value;
  6.     struct Node *next;
  7. };
  8. typedef struct Node Node;
  9. struct Node *head = NULL;
  10.  
  11. void Insertion(int ele){
  12.     Node *temp = new Node;
  13.     if( temp == NULL){
  14.         printf("\nmemory is not allocated");
  15.         return;
  16.     }
  17.     temp->value = ele;
  18.     if(S_size==0){
  19.         temp->next = head;
  20.         head = temp;
  21.     }
  22.     else{
  23.         struct Node *ptr = head;
  24.         int point = S_size-1;
  25.         while(point--){
  26.             ptr = ptr->next;
  27.         }
  28.         temp->next = ptr->next;
  29.         ptr->next = temp;
  30.     }
  31.     S_size++;
  32. }
  33. void Deletion(){
  34.     if(head == NULL){
  35.         printf("\nStack is empty");
  36.         return;
  37.     }
  38.     Node* dele = head;
  39.     if(S_size == 1){
  40.         head = NULL;
  41.         free(dele);
  42.     }
  43.     else{
  44.         Node *ptr = head;
  45.         int point = S_size-2;
  46.         while(point--){
  47.             ptr = ptr->next;
  48.         }
  49.         dele = ptr->next;
  50.         ptr->next = ptr->next->next;
  51.         free(dele);
  52.     }
  53.     S_size--;
  54. }
  55. void Print(){
  56.     Node *ptr  = head;
  57.     while(ptr != NULL){
  58.         printf("%d ",ptr->value);
  59.         ptr = ptr->next;
  60.     }
  61. }
  62. int main()
  63. {
  64.     int choice,ele,key;
  65.     while(1){
  66.         printf("\n1 for insertion\n2 for deletion\nany to key just print the stack\n");
  67.         scanf("%d",&choice);
  68.         if(choice == 1){
  69.             printf("\nEnter the element ");
  70.             scanf("%d",&ele);
  71.             Insertion(ele);
  72.         }
  73.         else if (choice == 2){
  74.             Deletion();
  75.         }
  76.         else Print();
  77.         printf("\n1 to repeat and any key to exit ");
  78.         scanf("%d",&key);
  79.         if(key != 1) break;
  80.     }
  81.     return 0;
  82. }
Advertisement
Add Comment
Please, Sign In to add comment