• Implement Queue using Stacks


    class Queue {
    public:
       stack<int>sta1;
       stack<int>sta2;
        // Push element x to the back of queue.
        /*
        入栈:把元素push到sta1中;
        出栈:sta2作为辅助栈,如果sta2不为空,则把sta2中的元素挨个出站,然后把sta1的元素压入sta2中,把栈顶元素出栈.最后要把sta2中的元素压入sta1中
        */
        void push(int x) {
            sta1.push(x);
           
           
        }

        // Removes the element from in front of queue.
        void pop(void) {
           
            while( !sta1.empty())
            { sta2.push(sta1.top());
             sta1.pop();
            }
            sta2.pop();
            while( !sta2.empty())//pop()之后要把sta2中的元素压入sta1中
            {
            sta1.push(sta2.top());
            sta2.pop();
            }
        }

        // Get the front element.
        int peek(void) {
            int a = 0;

            while(!sta1.empty())
            {sta2.push(sta1.top());
             sta1.pop();
            }
            a=sta2.top();
            while( !sta2.empty())//pop()之后要把sta2中的元素压入sta1中
            {
            sta1.push(sta2.top());
            sta2.pop();
            }
            return a;
        }

        // Return whether the queue is empty.
        bool empty(void) {
           
          return ( sta1.empty() && sta2.empty());
           
        }
    };

  • 相关阅读:
    团队冲刺第二阶段2
    团队冲刺第二阶段1
    第十二周总结
    团队游戏
    三个和尚
    第十一周总结
    第十周总结
    调用摄像头拍照
    怎样从相册中选择照片?
    怎样插入并播放音频?
  • 原文地址:https://www.cnblogs.com/gofighting/p/5036199.html
Copyright © 2020-2023  润新知