[LeetCode]Implement Queue using Stacks

本文介绍了一种利用两个栈来实现队列的方法。通过将入队操作映射为向PushStack压入元素,出队操作映射为从PopStack弹出元素的方式,实现了队列的基本功能。当PopStack为空时,将PushStack中的所有元素依次转移到PopStack中。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

解题思路:
1,使用2个stack,一个叫PushStack,一个叫PopStack。
2,每当Queue新进来一个element时,就把它加入到PushStack,
3,当Queue执行Pop操作时,从PopStack取出element。
4,当PopStack为空时,把PushStack的元素一个一个的加入到PopStack

数据如何从pushStack到popStack
1,popStack必须为空,pushStack非空;
2,element = pushStack.top()
     popStack.push(element)
     pushStack.pop()
3,反复执行步骤2,直到pushStack为空

// 编译错误

1,Stack不是一个已经定义的类型。应该小写s的  stack 


class Queue {
public:
    // Push element x to the back of queue.
    void push(int x) {
        pushStack.push(x);
    }

    // Removes the element from in front of queue.
    void pop(void) {
        if (empty()){
            // EXCLUDE IN THIS PROBLEM
        }
        if (popStack.empty() && !pushStack.empty()){
            tansportation();
        }
        return popStack.pop();
    }

    // Get the front element.
    int peek(void) {
        if (empty()){
            // EXCLUDE IN THIS PROBLEM
        }
        if (popStack.empty() && !pushStack.empty()){
            tansportation();
        }
        return popStack.top();
    }

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

    void tansportation(void){
        if (popStack.empty() && !pushStack.empty()){
            while(!pushStack.empty()){
                int elem = pushStack.top();
                popStack.push(elem);
                pushStack.pop();
            }
        }
    }
private:
    stack<int> pushStack;
    stack<int> popStack;
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值