添加内容

This commit is contained in:
YDZ
2020-08-08 09:17:26 +08:00
parent 5015cc6b7b
commit fdba30f0c4
734 changed files with 4024 additions and 2129 deletions

View File

@ -0,0 +1,99 @@
# [232. Implement Queue using Stacks](https://leetcode.com/problems/implement-queue-using-stacks/)
## 题目
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.
**Example**:
```
MyQueue queue = new MyQueue();
queue.push(1);
queue.push(2);
queue.peek(); // returns 1
queue.pop(); // returns 1
queue.empty(); // returns false
```
**Note**:
- You must use only standard operations of a stack -- which means only push to top, peek/pop from top, size, 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).
## 题目大意
题目要求用栈实现一个队列的基本操作push(x)、pop()、peek()、empty()。
## 解题思路
按照题目要求实现即可。
## 代码
```go
package leetcode
type MyQueue struct {
Stack *[]int
Queue *[]int
}
/** Initialize your data structure here. */
func Constructor232() MyQueue {
tmp1, tmp2 := []int{}, []int{}
return MyQueue{Stack: &tmp1, Queue: &tmp2}
}
/** Push element x to the back of queue. */
func (this *MyQueue) Push(x int) {
*this.Stack = append(*this.Stack, x)
}
/** Removes the element from in front of queue and returns that element. */
func (this *MyQueue) Pop() int {
if len(*this.Queue) == 0 {
this.fromStackToQueue(this.Stack, this.Queue)
}
popped := (*this.Queue)[len(*this.Queue)-1]
*this.Queue = (*this.Queue)[:len(*this.Queue)-1]
return popped
}
/** Get the front element. */
func (this *MyQueue) Peek() int {
if len(*this.Queue) == 0 {
this.fromStackToQueue(this.Stack, this.Queue)
}
return (*this.Queue)[len(*this.Queue)-1]
}
/** Returns whether the queue is empty. */
func (this *MyQueue) Empty() bool {
return len(*this.Stack)+len(*this.Queue) == 0
}
func (this *MyQueue) fromStackToQueue(s, q *[]int) {
for len(*s) > 0 {
popped := (*s)[len(*s)-1]
*s = (*s)[:len(*s)-1]
*q = append(*q, popped)
}
}
```