用两个栈实现队列

    xiaoxiao2023-11-03  177

    题目描述

    用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。

    class Solution { public: void push(int node) { while(!stack1.empty()) { stack2.push(stack1.top()); stack1.pop(); } stack1.push(node); while(!stack2.empty()) { stack1.push(stack2.top()); stack2.pop(); } } /*确保每次进来的数据都在栈底,即确保每次出栈的都是呆的最久的那个数据即可*/ int pop() { int a = stack1.top(); stack1.pop(); return a; } private: stack<int> stack1; stack<int> stack2; };

     

    最新回复(0)