Advertisement
Guest User

Untitled

a guest
Mar 22nd, 2019
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.83 KB | None | 0 0
  1. #include "pch.h"
  2. #include <iostream>
  3. using namespace std;
  4.  
  5.  
  6. struct Node
  7. {
  8.     int val;
  9.     struct Node *next;
  10. };
  11.  
  12. struct Node* stack_push(struct Node* h, int val)
  13. {
  14.     struct Node* cur = (struct Node*)
  15.         malloc(sizeof(struct Node));
  16.  
  17.     cur->val = val;
  18.     cur->next = h;
  19.     h = cur;
  20.  
  21.     return h;
  22. };
  23.  
  24.  
  25.  
  26.  
  27. struct Node* stack_pop(struct Node* h)
  28. {
  29.     Node* cur = h;
  30.  
  31.     if (cur != NULL)
  32.     {
  33.         h = cur->next;
  34.         free(cur);
  35.         cur->val = NULL;
  36.         cur->next = NULL;
  37.     }
  38.  
  39.     return h;
  40. };
  41.  
  42.  
  43. void stack_show(Node* h)
  44. {
  45.     Node* cur = h;
  46.     while (cur)
  47.     {
  48.         cout << cur->val << " ";
  49.  
  50.         cur = cur->next;
  51.     }
  52.  
  53.     cout << endl;
  54. };
  55.  
  56. int main()
  57. {
  58.     struct Node* head = NULL;
  59.     struct Node* tail = NULL;
  60.  
  61.  
  62.     head = stack_push(head, 5);
  63.     head = stack_push(head, 10);
  64.     head = stack_push(head, 20);
  65.  
  66.  
  67.     stack_show(head);
  68.     head = stack_pop(head);
  69.  
  70.  
  71.     stack_show(head);
  72.     head = stack_pop(head);
  73.  
  74.  
  75.     stack_show(head);
  76.     head = stack_pop(head);
  77.  
  78.     stack_show(head);
  79.  
  80.  
  81.     return 0;
  82.  
  83.    
  84. }
  85. void push_queue(struct Node* tail, int val){
  86.    
  87.     if(tail==head){
  88.         struct Node* cur = (struct Node*)malloc(sizeof(struct Node));
  89.         cur->val=val;
  90.         cur->next =NULL;
  91.         tail=cur;
  92.         head->next = tail;
  93.     }
  94.     if(tail==NULL){
  95.         head->val = tail->val = val;
  96.         head->next = tail->next = NULL;
  97.     }
  98.     struct Node* cur = (struct Node*)malloc(sizeof(struct Node));
  99.     cur->next = NULL;
  100.     cur->val = val;
  101.     tail->next=cur;
  102.     tail = cur;
  103. }
  104.  
  105. struct Node* pop_queue(struct Node* head, int val){
  106.     Node* cur = head;
  107.     if(head==NULL){
  108.         cout << "queue is empty" << endl;
  109.         return 0;
  110.     }
  111.     head=head->next;
  112.     return cur;
  113. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement