力扣232:用栈实现队列
请你仅使用两个栈实现先入先出队列。队列应当支持一般队列支持的所有操作(push
、pop
、peek
、empty
):
实现 MyQueue
类:
void push(int x)
将元素 x 推到队列的末尾int pop()
从队列的开头移除并返回元素int peek()
返回队列开头的元素boolean empty()
如果队列为空,返回true
;否则,返回false
说明:
- 你 只能 使用标准的栈操作 —— 也就是只有
push to top
,peek/pop from top
,size
, 和is empty
操作是合法的。 - 你所使用的语言也许不支持栈。你可以使用 list 或者 deque(双端队列)来模拟一个栈,只要是标准的栈操作即可。
示例 1:
输入: ["MyQueue", "push", "push", "peek", "pop", "empty"] [[], [1], [2], [], [], []] 输出: [null, null, null, 1, 1, false]解释: MyQueue myQueue = new MyQueue(); myQueue.push(1); // queue is: [1] myQueue.push(2); // queue is: [1, 2] (leftmost is front of the queue) myQueue.peek(); // return 1 myQueue.pop(); // return 1, queue is [2] myQueue.empty(); // return false
思想:
用两个栈实现队列操作, 队列为先进先出, 栈为先进后出;
元素入队, 进入S1;
元素出队, S2不为空, S2栈顶元素弹出, S2为空, 将S1元素弹出进入S2, 再从S2栈顶弹出
代码:
typedef struct {int stack1[100];int top1;int stack2[100];int top2;
} MyQueue;MyQueue* myQueueCreate() {MyQueue *obj = (MyQueue*)malloc(sizeof(MyQueue));obj->top1 = 0;obj->top2 = 0;return obj;
}void myQueuePush(MyQueue* obj, int x) {obj->stack1[obj->top1++] = x; /* 入队到S1 */
}int myQueuePop(MyQueue* obj) {if (obj->top2 == 0) {while (obj->top1 != 0) { /* S1元素弹出, 进入S2 */obj->stack2[obj->top2++] = obj->stack1[--obj->top1];}}return obj->stack2[--obj->top2]; /* 从S2中弹出元素 */
}int myQueuePeek(MyQueue* obj) {if (obj->top2 == 0) {while (obj->top1 != 0) { /* S1元素弹出, 进入S2 */obj->stack2[obj->top2++] = obj->stack1[--obj->top1];}}return obj->stack2[obj->top2 - 1]; /* 获取栈顶元素, 不用弹出元素 */
}bool myQueueEmpty(MyQueue* obj) {return obj->top1 == 0 && obj->top2 == 0;
}void myQueueFree(MyQueue* obj) {free(obj);
}