+关注继续查看

📢 ：❤布小禅❤

📢 作者专栏：

❤力扣题❤

# 💗 一、题目描述 💗

void push(int x) 将元素 x 推到队列的末尾

int pop() 从队列的开头移除并返回元素

int peek() 返回队列开头的元素

boolean empty() 如果队列为空，返回 true ；否则，返回 false。

输入：
["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

**进阶：

**

1 <= x <= 9

# 💁 二、题目解析 💁

s1作为接收入队元素的栈，s2作为出队的栈

# 🏃 三、代码 🏃

## ☁️ 1️⃣. python ☁️

class MyQueue:

def __init__(self):
"""
"""
self.s1 = []
self.s2 = []

def push(self, x: int) -> None:
"""
Push element x to the back of queue.
"""
while len(self.s2)!=0:
self.s1.append(self.s2.pop())
self.s1.append(x)

def pop(self) -> int:
"""
Removes the element from in front of queue and returns that element.
"""
while len(self.s1)!=0:
self.s2.append(self.s1.pop())
return self.s2.pop()

def peek(self) -> int:
"""
Get the front element.
"""
while len(self.s1)!=0:
self.s2.append(self.s1.pop())
return self.s2[-1]

def empty(self) -> bool:
"""
Returns whether the queue is empty.
"""
if len(self.s1)==0 and len(self.s2)==0: return True
else: return False

# Your MyQueue object will be instantiated and called as such:
# obj = MyQueue()
# obj.push(x)
# param_2 = obj.pop()
# param_3 = obj.peek()
# param_4 = obj.empty()

## ❄️ 2️⃣. C# ❄️

public class MyQueue
{
private Stack s1;
private Stack s2;
/** Initialize your data structure here. */
public MyQueue()
{
s1 = new Stack();
s2 = new Stack();
}

/** Push element x to the back of queue. */
public void Push(int x)
{
while (s2.Count != 0)
{
s1.Push(s2.Pop());
}
s1.Push(x);
}

/** Removes the element from in front of queue and returns that element. */
public int Pop()
{
while (s1.Count != 0)
{
s2.Push(s1.Pop());
}
return (int)s2.Pop();
}

/** Get the front element. */
public int Peek()
{
while (s1.Count != 0)
{
s2.Push(s1.Pop());
}
return (int)s2.Peek();
}

/** Returns whether the queue is empty. */
public bool Empty()
{
if (s1.Count == 0 && s2.Count == 0) return true;
else return false;
}
}


# 🌔 结语 🌔

9627 0

11330 0

13345 0
windows server 2008阿里云ECS服务器安全设置

9083 0

4627 0

7399 0

22052 0
+关注

153

0

《2021云上架构与运维峰会演讲合集》

《零基础CSS入门教程》

《零基础HTML入门教程》