232 - Implement Queue using Stacks

本文介绍了一种利用栈来实现队列的方法,并提供了一个具体的C++实现案例。该方法通过两个栈来模拟队列的基本操作,包括入队、出队、获取队首元素及判断队列是否为空。

Implement the following operations of a queue using stacks.

  • push(x) -- Push element x to the back of queue.
  • pop() -- Removes the element from in front of queue.
  • peek() -- Get the front element.
  • empty() -- Return whether the queue is empty.
Notes:
  • You must use only standard operations of a stack -- which means only push to toppeek/pop from topsize, and is empty operations are valid.
  • Depending on your language, stack may not be supported natively. You may simulate a stack by using a list or deque (double-ended queue), as long as you use only standard operations of a stack.

  • You may assume that all operations are valid (for example, no pop or peek operations will be called on an empty queue).

实现如下:
class Queue {
public:
         stack<int> A, B;
        void push(int x) {
                A.push(x);
        }

        void pop(void) {
                while(!A.empty()) {
                        B.push(A.top());
                        A.pop();
                }
                B.pop();
                while(!B.empty()) {
                        A.push(B.top());
                        B.pop();
                }
        }

        int peek(void) {
                if( !A.empty() ) {
                        while(!A.empty()) {
                                B.push(A.top());
                                A.pop();
                        }
                        int p = B.top();
                        while(!B.empty()) {
                                A.push(B.top());
                                B.pop();
                        }
                        return p;
                }
                return 0;
        }

        bool empty(void) {
                return A.empty();
        }
};

int main() {
        Queue queue;
        queue.push(1);
        queue.push(2);
        queue.push(3);
        while(!queue.empty()) {
                cout << queue.peek();
                queue.pop();
        }
        //queue.pop();
        cout << queue.peek() << endl;
        if(queue.empty() == true)
                cout << "empty" << endl;
        else
                cout << "not empty" << endl;
        return 0;
}


typedef struct { int* stk; int stkSize; int stkCapacity; } Stack; Stack* stackCreate(int cpacity) { Stack* ret = malloc(sizeof(Stack)); ret->stk = malloc(sizeof(int) * cpacity); ret->stkSize = 0; ret->stkCapacity = cpacity; return ret; } void stackPush(Stack* obj, int x) { obj->stk[obj->stkSize++] = x; } void stackPop(Stack* obj) { obj->stkSize--; } int stackTop(Stack* obj) { return obj->stk[obj->stkSize - 1]; } bool stackEmpty(Stack* obj) { return obj->stkSize == 0; } void stackFree(Stack* obj) { free(obj->stk); } typedef struct { Stack* inStack; Stack* outStack; } MyQueue; MyQueue* myQueueCreate() { MyQueue* ret = malloc(sizeof(MyQueue)); ret->inStack = stackCreate(100); ret->outStack = stackCreate(100); return ret; } void in2out(MyQueue* obj) { while (!stackEmpty(obj->inStack)) { stackPush(obj->outStack, stackTop(obj->inStack)); stackPop(obj->inStack); } } void myQueuePush(MyQueue* obj, int x) { stackPush(obj->inStack, x); } int myQueuePop(MyQueue* obj) { if (stackEmpty(obj->outStack)) { in2out(obj); } int x = stackTop(obj->outStack); stackPop(obj->outStack); return x; } int myQueuePeek(MyQueue* obj) { if (stackEmpty(obj->outStack)) { in2out(obj); } return stackTop(obj->outStack); } bool myQueueEmpty(MyQueue* obj) { return stackEmpty(obj->inStack) && stackEmpty(obj->outStack); } void myQueueFree(MyQueue* obj) { stackFree(obj->inStack); stackFree(obj->outStack); } 作者:御三五 🥇 链接:https://leetcode.cn/problems/implement-queue-using-stacks/solutions/656774/tu-jie-guan-fang-tui-jian-ti-jie-yong-zh-4hru/ 来源:力扣(LeetCode) 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
最新发布
06-23
### 栈实现队列的原理 栈是一种后进先出(LIFO)的数据结构,而队列是一种先进先出(FIFO)的数据结构。为了用栈实现队列,需要使用两个栈来模拟队列的行为。一个栈用于入队操作(`push`),另一个栈用于出队操作(`pop` 和 `peek`)。通过将数据在两个栈之间转移,可以实现队列的 FIFO 特性[^1]。 当执行入队操作时,直接将元素压入第一个栈(`push_stack`)。当执行出队或查看队首元素操作时,如果第二个栈(`pop_stack`)为空,则将第一个栈中的所有元素依次弹出并压入第二个栈中。这样,原本后进先出的顺序被反转为先进先出的顺序[^4]。 ### 代码实现 以下是一个完整的用栈实现队列的代码示例: ```c #include <stdio.h> #include <stdlib.h> // 定义栈结构 typedef struct Stack { int* data; int top; int capacity; } Stack; // 初始化栈 void STInit(Stack* ps) { ps->data = NULL; ps->top = 0; ps->capacity = 0; } // 销毁栈 void STDestory(Stack* ps) { free(ps->data); ps->data = NULL; ps->top = ps->capacity = 0; } // 入栈 void STPush(Stack* ps, int x) { if (ps->top == ps->capacity) { int newCapacity = ps->capacity == 0 ? 4 : ps->capacity * 2; int* newData = (int*)realloc(ps->data, sizeof(int) * newCapacity); if (newData == NULL) { perror("realloc failed"); exit(-1); } ps->data = newData; ps->capacity = newCapacity; } ps->data[ps->top] = x; ps->top++; } // 出栈 void STPop(Stack* ps) { if (ps->top == 0) { return; } ps->top--; } // 获取栈顶元素 int STTop(Stack* ps) { if (ps->top == 0) { return -1; // 或者抛出异常 } return ps->data[ps->top - 1]; } // 判断栈是否为空 int STEmpty(Stack* ps) { return ps->top == 0; } // 定义队列结构 typedef struct MyQueue { Stack pushst; Stack popst; } MyQueue; // 初始化队列 void myQueueInit(MyQueue* obj) { STInit(&obj->pushst); STInit(&obj->popst); } // 销毁队列 void myQueueDestory(MyQueue* obj) { STDestory(&obj->pushst); STDestory(&obj->popst); } // 将元素X推到队列的末尾 void myQueuePush(MyQueue* obj, int x) { STPush(&obj->pushst, x); } // 从队列的开头移除并返回元素 int myQueuePop(MyQueue* obj) { if (STEmpty(&obj->popst)) { while (!STEmpty(&obj->pushst)) { STPush(&obj->popst, STTop(&obj->pushst)); STPop(&obj->pushst); } } int front = STTop(&obj->popst); STPop(&obj->popst); return front; } // 返回队列开头的元素 int myQueuePeek(MyQueue* obj) { if (STEmpty(&obj->popst)) { while (!STEmpty(&obj->pushst)) { STPush(&obj->popst, STTop(&obj->pushst)); STPop(&obj->pushst); } } return STTop(&obj->popst); } // 如果队列为空,返回 true;否则,返回 false int myQueueEmpty(MyQueue* obj) { return STEmpty(&obj->pushst) && STEmpty(&obj->popst); } ``` ### 代码解析 - **初始化与销毁**:`myQueueInit` 和 `myQueueDestory` 分别用于初始化和销毁队列。这两个函数主要负责初始化或释放两个栈的资源[^3]。 - **入队操作**:`myQueuePush` 将元素压入 `push_stack` 中。此操作的时间复杂度为 O(1)[^5]。 - **出队操作**:`myQueuePop` 首先检查 `pop_stack` 是否为空。如果为空,则将 `push_stack` 中的所有元素依次弹出并压入 `pop_stack`,从而反转顺序。然后从 `pop_stack` 中弹出栈顶元素作为队列的前端元素[^4]。 - **查看队首元素**:`myQueuePeek` 的逻辑与 `myQueuePop` 类似,但不会移除元素[^5]。 - **判断队列是否为空**:`myQueueEmpty` 检查两个栈是否都为空。如果两个栈均为空,则队列为空。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值