两个队列模拟一个栈行为;

两个队列q1,q2,队列构造函数默认构造两个空队列。

将元素入队到q1中,经过一系列入队操作,q1非空,含有n个元素,q2为空队;

将q1中元素依次出队并入队q2,直至只剩下一个元素, 即q1出队n-1个元素,并依次入队到q2中。

此时,q1中仅剩的唯一一个元素,是期初队列最后入队的元素,将该元素删除(pop),就模拟完成了栈的栈顶元素出栈;在删除之前取出该元素,就模拟完成了取栈顶元素 ,这和栈的后进先出一致

此时,q1,为空,q2非空,接下来要做的就是循环的对非空队列入队,取最后一个元素

  1 //两个队列模拟栈
  2 
  3 class SimulateStack
  4 {
  5 public:
  6     SimulateStack(){ count = 0;}
  7     ~SimulateStack(){ }
  8     void simPush(int); //模拟入栈
  9     void simPop(); //模拟出栈
 10     int simTop();//取栈顶元素
 11     int simSize();//计算栈元素个数;
 12     bool simEmpty();
 13 private:
 14     queue<int> q1;
 15     queue<int> q2;
 16     int count;
 17 };
 18 
 19 inline
 20 void SimulateStack::simPush(int num)
 21 {
 22     if (!q1.empty())
 23     {
 24         q1.push(num);
 25     }
 26     else
 27         q2.push(num);
 28     count++;
 29 }
 30 
 31 inline
 32 void SimulateStack::simPop()
 33 {
 34     //int tmp;
 35     if (!q1.empty())
 36     {
 37         while (q1.size()!=1)
 38         {
 39             q2.push(q1.front());
 40             q1.pop();
 41         }
 42         //tmp = q1.front();
 43         q1.pop();
 44     }
 45     else
 46         if (!q2.empty())
 47         {
 48             while (q2.size()!=1)
 49             {
 50                 q1.push(q2.front());
 51                 q2.pop();
 52             }
 53             //tmp = q2.front();
 54             q2.pop();
 55         }
 56     --count;
 57 }
 58 
 59 inline
 60 int SimulateStack::simTop()
 61 {
 62     int tmp;
 63     if (!q1.empty())
 64     {
 65         while (q1.size()!=1)
 66         {
 67             q2.push(q1.front());
 68             q1.pop();
 69         }
 70         tmp = q1.front();
 71         q1.pop();
 72     }
 73     else
 74         if (!q2.empty())
 75         {
 76             while (q2.size()!=1)
 77             {
 78                 q1.push(q2.front());
 79                 q2.pop();
 80             }
 81             tmp = q2.front();
 82             q2.pop();
 83         }
 84         //--count;
 85         return tmp;
 86 }
 87 inline
 88 int SimulateStack::simSize()
 89 {
 90     return count;
 91 }
 92 inline
 93 bool SimulateStack::simEmpty()
 94 {
 95     return (count == 0);
 96 }
 97 
 98 int main()
 99 {
100     SimulateStack st;
101     st.simPush(1);
102     st.simPush(2);
103     st.simPush(3);
104     st.simPush(4);
105     st.simPush(5);
106     
107     int st_size = st.simSize();
108     cout << "stack size: "<<st_size<<endl;
109 
110     for (int i = 0; i < st_size; ++i)
111     {
112         cout << st.simTop() << " ";
113     }
114 }

猜你喜欢

转载自www.cnblogs.com/strivingforever/p/9059667.html
今日推荐