O_Egor

Stack

Jan 9th, 2020 (edited)
419
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.00 KB | None | 0 0
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. //Реализация Stack на основе односвязного списка
  5. //Задача: попрано вывести индексы открывающих скобок и их закрывающих скокбок в строке
  6. struct el
  7. {
  8.     int num;
  9.     el* next;
  10. };
  11.  
  12. el* b;
  13.  
  14. el* newstack()
  15. {
  16.     b = new el;
  17.     b->next = NULL;
  18.     return b;
  19. }
  20.  
  21. void push_s(el*& a, int x)
  22. {
  23.     a->num = x;
  24.     b = a;
  25.     a = new el;
  26.     a->next = b;
  27. }
  28.  
  29. void pop(el*& a)
  30. {
  31.     b = a->next;
  32.     a->next = b->next;
  33.     delete b;
  34. }
  35.  
  36. el* newqueue()
  37. {
  38.     b = new el;
  39.     b->next = b;
  40.     return b;
  41. }
  42.  
  43. void push_q(el*& a, int x)
  44. {
  45.     a->num = x;
  46.     b = a;
  47.     a = new el;
  48.     a->next = b->next;
  49.     b->next = a;
  50. }
  51.  
  52. int top(el*& a)
  53. {
  54.     return a->next->num;
  55. }
  56.  
  57. bool isempty(el* a)
  58. {
  59.     return (a->next == NULL || a->next == a);
  60. }
  61.  
  62. void out(el*& open, el*& close1, el*& close2)
  63. {
  64.     while (!isempty(close1))
  65.     {
  66.         cout << top(open) << ' ' << top(close1) << "; ";
  67.         pop(open); pop(close1);
  68.     }
  69.     while (!isempty(close2))
  70.     {
  71.         cout << top(open) << ' ' << top(close2) << "; ";
  72.         pop(open); pop(close2);
  73.     }
  74. }
  75.  
  76. int main()
  77. {
  78.     el* open, * close2, * close1;
  79.     open = newqueue();
  80.     close2 = newqueue();
  81.     close1 = newstack();
  82.     char c;
  83.     int i = 0, k = 0;
  84.     bool f = 0;
  85.     while (cin >> c)
  86.     {
  87.         i++;
  88.         if (c == '(')
  89.         {
  90.             push_q(open, i);
  91.             f = 1;
  92.             k++;
  93.         }
  94.         else
  95.         {
  96.             if (c == ')')
  97.             {
  98.                 k--;
  99.                 if (f)
  100.                 {
  101.                     push_q(close2, i);
  102.                     f = 0;
  103.                 }
  104.                 else
  105.                     push_s(close1, i);
  106.             }
  107.         }
  108.         if (!k)
  109.             out(open, close1, close2);
  110.     }
  111.     out(open, close1, close2);
  112.     return 0;
  113. }
  114. /*
  115. 5+2*(13+(14-2))=0?
  116. */
Advertisement
Add Comment
Please, Sign In to add comment