面试题9-用两个栈实现队列

题目:

用两个栈实现一个队列。队列的声明如下,请实现它的两个函数appendTail和deleteHead,分别完成在队列尾部插入节点和在队列头部删除节点的功能。

template<typename T>class CQueue
{
public:
	CQueue(void);
	~CQueue(void);
	void appendTail(const T& node);
	T deleteHead();

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

解题思路:

将一个栈当作输入栈,用于压入appendTail 传入的数据;另一个栈当作输出栈,用于 deleteHead 操作。

每次 deleteHead 时,若输出栈为空则将输入栈的全部数据依次弹出并压入输出栈,这样输出栈从栈顶往栈底的顺序就是队列从队首往队尾的顺序。
创建两个栈stack1和stack2,使用两个“先进后出”的栈实现一个“先进先出”的队列。

我们通过一个具体的例子分析往该队列插入和删除元素的过程。首先插入一个元素a,不妨先把它插入到stack1,此时stack1中的元素有{a},stack2为空。再压入两个元素b和c,还是插入到stack1中,此时stack1的元素有{a,b,c},其中c位于栈顶,而stack2仍然是空的。

这个时候我们试着从队列中删除一个元素。按照先入先出的规则,由于a比b、c先插入队列中,最先删除的元素应该是a。元素a存储在stack1中,但并不在栈顶,因此不能直接进行删除操作。注意stack2我们一直没有使用过,现在是让stack2发挥作用的时候了。如果我们把stack1中的元素逐个弹出压入stack2,元素在stack2中的顺序正好和原来在stack1中的顺序相反。因此经过3次弹出stack1和要入stack2操作之后,stack1为空,而stack2中的元素是{c,b,a},这个时候就可以弹出stack2的栈顶a了。此时的stack1为空,而stack2的元素为{b,a},其中b在栈顶。

因此我们的思路是:当stack2中不为空时,在stack2中的栈顶元素是最先进入队列的元素,可以弹出。如果stack2为空时,我们把stack1中的元素逐个弹出并压入stack2。由于先进入队列的元素被压倒stack1的栈底,经过弹出和压入之后就处于stack2的栈顶,有可以直接弹出。如果有新元素d插入,我们直接把它压入stack1即可。

流程示意图:
在这里插入图片描述

C++实现

template<typename T>
void CQueue<T>::appendTail(const T& element)
{
	stack1.push(element);	
}
template<typename T>
T CQueue<T>::deleteHead() {
	if (stack2.size() <= 0)
	{
		while (stack1.size()>0)
		{
			T &data = stack1.top();
			stack1.pop();
			stack2.push(data);
		}
	}
	if (stack2.size() == 0)
	{
		throw new exception("queue is empty");
	}
	T head = stack2.top();
	stack2.pop();
	return head;
}
//测试用例
int  main(){
	CQueue<int>cq;
	//往stack1中添加元素
	cq.appendTail(1);
	cq.appendTail(2);
	cq.appendTail(3);
	cq.appendTail(4);
	//移除元素
	int res=cq.deleteHead();
	cq.deleteHead();
	cq.deleteHead();
	cq.deleteHead();
	cq.deleteHead();
	cout << res << endl;
	cq.Print();
	system("pause");
	return 0;
}

Python实现

# -*- coding UTF-8 -*-
#@Time:2021/10/1018:18
#@File:9_用两个栈实现队列.py
#@Software:PyCharm
class Solution:
    def __init__(self):
        self.stack1=[]
        self.stack2=[]
    def push(self,node):
        self.stack1.append(node)
    def pop(self):
        if(len(self.stack2)==0):
            while self.stack1:
                self.stack2.append(self.stack1.pop())
        try:
            return self.stack2.pop()
        except:
            print("队列为空")
# 测试用例
if __name__=="__main__":
    s=Solution()
    s.push(1)
    s.push(2)
    s.push(3)
    s.push(4)
    s.pop()
    s.pop()
    s.pop()
    s.pop()
    s.pop()

测试用例

  1. 往空的队列中添加、删除元素
  2. 往非空的队列中添加、删除元素
  3. 连续删除元素直至队列为空

拓展

用两个队列实现栈

为了满足栈的特性,即最后入栈的元素最先出栈,在使用队列实现栈时,应满足队列前端的元素是最后入栈的元素。可以使用两个队列实现栈的操作,其中 queue 1用于存储栈内的元素,queue2作为入栈操作的辅助队列。
入栈操作时,首先将元素入队到 queue2,然后将queue1的全部元素依次出队并入队到queue2 ,此时queue2的前端的元素即为新入栈的元素,再将queue1 和 queue2互换,则 queue1的元素即为栈内的元素,queue1的前端和后端分别对应栈顶和栈底。
由于每次入栈操作都确保 queue1 的前端元素为栈顶元素,因此出栈操作和获得栈顶元素操作都可以简单实现。出栈操作只需要移除queue1的前端元素并返回即可,获得栈顶元素操作只需要获得 queue1 的前端元素并返回即可(不移除元素)。
由于 queue1用于存储栈内的元素,判断栈是否为空时,只需要判断 queue1是否为空即可。

//用两个队列实现栈
class MyStack {
public:
    queue<int> queue1;
    queue<int> queue2;

    /** Initialize your data structure here. */
    MyStack() {

    }

    /** Push element x onto stack. */
    void push(int x) {
        queue2.push(x);
        while (!queue1.empty()) {
            queue2.push(queue1.front());
            queue1.pop();
        }
        swap(queue1, queue2);
    }
    
    /** Removes the element on top of the stack and returns that element. */
    int pop() {
        int r = queue1.front();
        queue1.pop();
        return r;
    }
    
    /** Get the top element. */
    int top() {
        int r = queue1.front();
        return r;
    }
    
    /** Returns whether the stack is empty. */
    bool empty() {
        return queue1.empty();
    }
};
class MyStack:

    def __init__(self):
        """
        Initialize your data structure here.
        """
        self.queue1 = collections.deque()
        self.queue2 = collections.deque()


    def push(self, x: int) -> None:
        """
        Push element x onto stack.
        """
        self.queue2.append(x)
        while self.queue1:
            self.queue2.append(self.queue1.popleft()) # popleft:弹出最左端的元素
        self.queue1, self.queue2 = self.queue2, self.queue1


    def pop(self) -> int:
        """
        Removes the element on top of the stack and returns that element.
        """
        return self.queue1.popleft()


    def top(self) -> int:
        """
        Get the top element.
        """
        return self.queue1[0]


    def empty(self) -> bool:
        """
        Returns whether the stack is empty.
        """
        return not self.queue1

用一个队列实现栈

方法一使用了两个队列实现栈的操作,也可以使用一个队列实现栈的操作。

使用一个队列时,为了满足栈的特性,即最后入栈的元素最先出栈,同样需要满足队列前端的元素是最后入栈的元素。

入栈操作时,首先获得入栈前的元素个数 n,然后将元素入队到队列,再将队列中的前 n 个元素(即除了新入栈的元素之外的全部元素)依次出队并入队到队列,此时队列的前端的元素即为新入栈的元素,且队列的前端和后端分别对应栈顶和栈底。

由于每次入栈操作都确保队列的前端元素为栈顶元素,因此出栈操作和获得栈顶元素操作都可以简单实现。出栈操作只需要移除队列的前端元素并返回即可,获得栈顶元素操作只需要获得队列的前端元素并返回即可(不移除元素)。

由于队列用于存储栈内的元素,判断栈是否为空时,只需要判断队列是否为空即可。

class MyStack {
public:
    queue<int> q;

    /** Initialize your data structure here. */
    MyStack() {

    }

    /** Push element x onto stack. */
    void push(int x) {
        int n = q.size();
        q.push(x);
        for (int i = 0; i < n; i++) {
            q.push(q.front());
            q.pop();
        }
    }
    
    /** Removes the element on top of the stack and returns that element. */
    int pop() {
        int r = q.front();
        q.pop();
        return r;
    }
    
    /** Get the top element. */
    int top() {
        int r = q.front();
        return r;
    }
    
    /** Returns whether the stack is empty. */
    bool empty() {
        return q.empty();
    }
};
class MyStack:

    def __init__(self):
        """
        Initialize your data structure here.
        """
        self.queue = collections.deque()


    def push(self, x: int) -> None:
        """
        Push element x onto stack.
        """
        n = len(self.queue)
        self.queue.append(x)
        for _ in range(n):
            self.queue.append(self.queue.popleft())


    def pop(self) -> int:
        """
        Removes the element on top of the stack and returns that element.
        """
        return self.queue.popleft()


    def top(self) -> int:
        """
        Get the top element.
        """
        return self.queue[0]


    def empty(self) -> bool:
        """
        Returns whether the stack is empty.
        """
        return not self.queue
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值