用栈实现队列

用栈实现队列,需要两个栈,一个定义为stackIn,另一个定义为stackOut
牛客NC76 用两个栈实现队列

1、队列的push()操作

这个直接将数据压入stcakIn,就行

void push(int node) {
	stackIn.push(node);
}

2、队列的pop()操作

这里有两种解法

解法一:

当stcakOut为空时再将stackIn中的数据全部压入stackOut,当stackOut不为空时,直接stackOut.pop()就行

int pop() {
// 只有当stOut为空的时候,再从stIn里导入数据(导入stIn全部数据)
	if (stOut.empty()) {
// 从stIn导入数据直到stIn为空
		while(!stIn.empty()) {
			stOut.push(stIn.top());
			stIn.pop();
		}
	}
	int result = stOut.top();
	stOut.pop();
	return result;
}

解法二:

每次出栈后直接将stack.Out数据全部压回stack.In

int pop() {
//将第一个栈中内容弹出放入第二个栈中
	while (!stack1.empty()) {
		stack2.push(stack1.top());
		stack1.pop();
	}
//第二个栈栈顶就是最先进来的元素,即队首
	int res = stack2.top();
	stack2.pop();
//再将第二个栈的元素放回第一个栈
	while (!stack2.empty()) {
		stack1.push(stack2.top());
		stack2.pop();
	}
	return res;
}

之所以这样操作是因为队列不是一次性全部输入再全部输出,也就是说pop()后会接push()也会接pop()。

完整代码:

class Solution {
    stack<int> stackIn;
    stack<int> stackOut;
  public:
    void push(int node) {
        stackIn.push(node);
    }

//解法一:
    int pop() {
        if (stackOut.empty()) {
            while (!stackIn.empty()) {
                stackOut.push(stackIn.top());
                stackIn.pop();
            }
        }
        int result = stackOut.top();
        stackOut.pop();
        return result;
    }

//解法二:
	int pop() {
        //将第一个栈中内容弹出放入第二个栈中
        while (!stack1.empty()) {
            stack2.push(stack1.top());
            stack1.pop();
        }
        //第二个栈栈顶就是最先进来的元素,即队首
        int res = stack2.top();
        stack2.pop();
        //再将第二个栈的元素放回第一个栈
        while (!stack2.empty()) {
            stack1.push(stack2.top());
            stack2.pop();
        }
        return res;
    }

  private:
    stack<int> stack1;
    stack<int> stack2;
};
posted @ 2024-03-10 09:57  go__Ahead  阅读(1)  评论(0编辑  收藏  举报