剑指offer——5.用两个栈实现队列

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/N1neDing/article/details/81876981

题目描述:

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

解题思路:

使用stack1作为push进入操作的栈,stack2作为pop操作的栈,每次需要进行push时都将其push进stack1,需要pop时将stack2顶部元素pop出,如果stack2为空,则将stack1中元素从最尾到头push进stack2中,则实现了顺序颠倒,模拟出了队列的实现方式。

参考源码:

class Solution
{
public:
	void push(int node) {
		stack1.push(node);
	}

	int pop() {
		if (!stack2.empty())
		{
            int res = stack2.top();
			stack2.pop();
            return res;
		}
		else
		{
			if (!stack1.empty())
			{
				while (!stack1.empty())
				{
					stack2.push(stack1.top());
					stack1.pop();
				}
                int res = stack2.top();
				stack2.pop();
                return res;
			}
			else
			{
				return NULL;
			}
		}
	}

private:
	stack<int> stack1;
	stack<int> stack2;
};

相关题目:

用两个队列实现一个栈的功能。

解题思路:

每次pop时,将queue1中的元素依次push进queue2直到只剩下最后一个元素,将其pop,下次pop对queue2进行相同的操作即可。

push时,则直接将元素加在有元素的那个队列。

猜你喜欢

转载自blog.csdn.net/N1neDing/article/details/81876981