Advertisement
Guest User

Untitled

a guest
Oct 11th, 2018
141
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.40 KB | None | 0 0
  1. #include <iostream>
  2.  
  3. using namespace std;
  4.  
  5. struct Usel
  6. {
  7.     int key;
  8.  
  9.     Usel *next;
  10. };
  11.  
  12. struct Stack
  13. {
  14.     Usel * head;
  15.  
  16.     Stack() : head(0) {}
  17.  
  18.     Usel * Push(int k)
  19.     {
  20.         Usel* p;
  21.         p = new Usel;
  22.  
  23.         p->key = k; p->next = head;
  24.  
  25.         head = p; return head;
  26.     }
  27.  
  28.     int Pop()
  29.     {
  30.         Usel *p = head;
  31.  
  32.         int k = head->key;
  33.  
  34.         head = head->next;
  35.  
  36.         delete p;
  37.  
  38.         return k;
  39.     }
  40.  
  41.     void Print()
  42.     {
  43.         Usel *p;
  44.  
  45.         for (p = head; p; p = p->next)
  46.         {
  47.             cout << p->key << " ";
  48.         }
  49.     }
  50.  
  51.     void Del()
  52.     {
  53.         Usel* p;
  54.  
  55.         while (head)
  56.         {
  57.             p = head;
  58.  
  59.             head = head->next;
  60.  
  61.             delete p;
  62.         }
  63.     }
  64.  
  65.     bool Empty()
  66.     {
  67.         return head == 0 ? true : false;
  68.     }
  69. };
  70.  
  71. void Han(Stack *st, int n, int from, int help, int to)
  72. {
  73.     if (n == 1)
  74.     {
  75.         int k = st[from].Pop();
  76.         st[to].Push(k);
  77.  
  78.         puts("\nWorking...");
  79.  
  80.         st[2].Print(); cout << endl;
  81.  
  82.         st[1].Print(); cout << endl;
  83.        
  84.         st[0].Print();
  85.     }
  86.  
  87.     else
  88.     {
  89.         Han(st, n - 1, from, to, help);
  90.  
  91.         Han(st, 1, from, help, to);
  92.  
  93.         Han(st, n - 1, help, from, to);
  94.     }
  95.  
  96. }
  97.  
  98. int main()
  99. {
  100.     Stack st[3];
  101.     unsigned int n;
  102.  
  103.     cout << "Enter the n, please: ";
  104.     cin >> n;
  105.  
  106.     for (int i = n; i; i--)
  107.     {
  108.         st[2].Push(i);
  109.     }
  110.     st[2].Print();
  111.  
  112.     if (n != 0)
  113.     {
  114.         Han(st, n, 2, 1, 0);
  115.     }
  116.     cout << endl;
  117.  
  118.     for (int i = 0; i < 3; i++)
  119.     {
  120.         if (st[i].Empty())
  121.         {
  122.             st[i].Del();
  123.         }
  124.     }
  125.    
  126.     system("pause");
  127.     return 0;
  128. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement