--- title: 'LeetCode 225. Implement Stack using Queues' disqus: hackmd --- # LeetCode 225. Implement Stack using Queues ## Description Implement a last-in-first-out (LIFO) stack using only two queues. The implemented stack should support all the functions of a normal stack (push, top, pop, and empty). Implement the MyStack class: * void push(int x) Pushes element x to the top of the stack. * int pop() Removes the element on the top of the stack and returns it. * int top() Returns the element on the top of the stack. * boolean empty() Returns true if the stack is empty, false otherwise. Notes: * You must use only standard operations of a queue, which means that only push to back, peek/pop from front, size and is empty operations are valid. * Depending on your language, the queue may not be supported natively. You may simulate a queue using a list or deque (double-ended queue) as long as you use only a queue's standard operations. ## Example Input ["MyStack", "push", "push", "top", "pop", "empty"] [[], [1], [2], [], [], []] Output [null, null, null, 2, 2, false] Explanation MyStack myStack = new MyStack(); myStack.push(1); myStack.push(2); myStack.top(); // return 2 myStack.pop(); // return 2 myStack.empty(); // return False ## Constraints 1 <= x <= 9 At most 100 calls will be made to push, pop, top, and empty. All the calls to pop and top are valid. ## Answer 此題可用Queue的概念 (FIFO) 實現stack (LIFO),比較需要注意的就是用兩個Queue就可模擬stack,在pop時就將Q1從頭塞到Q2直到最後一個,然後將最後一個pop出去,再將Q1 & Q2做SWAP即可,相當於拿Q2來暫存。 ```Cin= typedef struct { int *Q1; int *Q2; int max; int top; } MyStack; MyStack* myStackCreate() { MyStack *obj = (MyStack*)malloc(sizeof(MyStack)); obj->max = 100; obj->top = 0; obj->Q1 = (int*)malloc(sizeof(int)*(obj->max)); obj->Q2 = (int*)malloc(sizeof(int)*(obj->max)); return obj; } void myStackPush(MyStack* obj, int x) { if(obj->top < obj->max){ obj->Q1[obj->top] = x; (obj->top)++; } } int myStackPop(MyStack* obj) { int ans = 0, i = 0; int *temp = NULL; if(obj->top > 0){ for(i = 0; i < obj->top - 1; i++){obj->Q2[i] = obj->Q1[i];} ans = obj->Q1[i]; (obj->top)--; temp = obj->Q1; obj->Q1 = obj->Q2; obj->Q2 = temp; } return ans; } int myStackTop(MyStack* obj) { int ans = 0; if(obj->top > 0){ ans = obj->Q1[obj->top - 1]; } return ans; } bool myStackEmpty(MyStack* obj) { return obj->top == 0; } void myStackFree(MyStack* obj) { free(obj->Q1); free(obj->Q2); free(obj); } ``` ## Link https://leetcode.com/problems/implement-stack-using-queues/ ###### tags: `Leetcode`