用队列实现栈

使用队列实现栈的下列操作:

push(x) -- 元素 x 入栈
pop() -- 移除栈顶元素
top() -- 获取栈顶元素
empty() -- 返回栈是否为空
注意:

你只能使用队列的基本操作-- 也就是 push to back, peek/pop from front, size, 和 is empty 这些操作是合法的。
你所使用的语言也许不支持队列。 你可以使用 list 或者 deque(双端队列)来模拟一个队列 , 只要是标准的队列操作即可。
你可以假设所有操作都是有效的(例如, 对一个空的栈不会调用 pop 或者 top 操作)。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/implement-stack-using-queues
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

 

思路:用队列实现栈的先进后出,为了保持每次刚进元素,始终位于队首,可以每次进队的之后,都把队里其他的元素弹出来,然后进队,即放在了当前元素的后面,保证了每次进的都在队首。

class MyStack {
public:
    
    /** Initialize your data structure here. */
    queue<int>q;
    MyStack() {

    }
    
    /** Push element x onto stack. */
    void push(int x) {
        q.push(x);
        for(int i=0;i<q.size()-1;i++){
            q.push(q.front());
            q.pop();
        }
    }
    
    /** Removes the element on top of the stack and returns that element. */
    int pop() {
        int t = q.front();
        q.pop();
        return t;

    }
    
    /** Get the top element. */
    int top() {
        return q.front();
    }
    
    /** Returns whether the stack is empty. */
    bool empty() {
        return (q.size()==0);
    }
};

/**
 * Your MyStack object will be instantiated and called as such:
 * MyStack* obj = new MyStack();
 * obj->push(x);
 * int param_2 = obj->pop();
 * int param_3 = obj->top();
 * bool param_4 = obj->empty();
 */

用队列实现栈只需要一个队列,而用栈实现队列则需要连个栈哈

使用队列实现的操作,关键在于利用两个队列(通常称为 `q1` 和 `q2`)来模拟的后进先出(LIFO)行为。具体来说,可以通过在每次插或删除操作时合理地管理这两个队列,从而实现的基本功能,包括 **push**、**pop**、**top** 和 **empty** 操作。 ### 用队列实现的核心思路 #### 1. 数据结构定义 首先定义一个结构,其中包含两个队列 `q1` 和 `q2`: ```c typedef struct { Queue q1; Queue q2; } MyStack; ``` 初始化时,需要对两个队列进行初始化[^3]。 #### 2. Push 操作 为了实现的 `push` 操作,始终将新元素添加到非空队列的末尾。如果两个队列都为空,则可以选择任意一个队列进行插。 ```c void myStackPush(MyStack* obj, int x) { if (!QueueEmpty(&obj->q1)) { QueuePush(&obj->q1, x); } else { QueuePush(&obj->q2, x); } } ``` #### 3. Pop 操作 的 `pop` 操作要求移除并返回最后一个被插的元素。为此,需要将当前非空队列中的前 `n-1` 个元素移动到另一个空队列中,然后移除最后一个元素。 ```c int myStackPop(MyStack* obj) { Queue* nonEmptyQueue = &obj->q1; Queue* emptyQueue = &obj->q2; if (QueueEmpty(nonEmptyQueue)) { nonEmptyQueue = &obj->q2; emptyQueue = &obj->q1; } while (QueueSize(nonEmptyQueue) > 1) { int front = QueueFront(nonEmptyQueue); QueuePop(nonEmptyQueue); QueuePush(emptyQueue, front); } int topElement = QueueFront(nonEmptyQueue); QueuePop(nonEmptyQueue); return topElement; } ``` 通过这种方式,实现的后进先出特性[^2]。 #### 4. Top 操作 获取顶元素时,逻辑与 `pop` 类似,只是不真正移除最后一个元素。 ```c int myStackTop(MyStack* obj) { Queue* nonEmptyQueue = &obj->q1; Queue* emptyQueue = &obj->q2; if (QueueEmpty(nonEmptyQueue)) { nonEmptyQueue = &obj->q2; emptyQueue = &obj->q1; } while (QueueSize(nonEmptyQueue) > 1) { int front = QueueFront(nonEmptyQueue); QueuePop(nonEmptyQueue); QueuePush(emptyQueue, front); } return QueueFront(nonEmptyQueue); } ``` #### 5. Empty 操作 判断是否为空,只需检查两个队列是否同时为空。 ```c bool myStackEmpty(MyStack* obj) { return QueueEmpty(&obj->q1) && QueueEmpty(&obj->q2); } ``` ### 总结 通过上述方法,可以有效地使用两个队列实现的功能。每个操作的时间复杂度如下: - **Push**: $ O(1) $ - **Pop**: $ O(n) $ - **Top**: $ O(n) $ - **Empty**: $ O(1) $ 这种实现方式虽然在 `pop` 和 `top` 操作上效率较低,但能够很好地体现队列之间的关系,并且适用于某些特定场景下的教学或实践需求。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值