代码随想录刷题第十天
栈和队列
在Python中,没有一个具体的栈或者队列的数据结构,只能用其他数据结构模拟栈、队列的结构。例如,使用列表 list()
来模拟栈,使用链表 deque()
来模拟队列.
栈:先进后出,永远只能访问栈顶的元素,栈顶元素是最后添加进入的,也是最先删除的。
队列:先进先出,类似排队,先进入队列的人先删除。
用栈实现队列 (LC 232)
使用栈实现队列的下列操作:
- push(x) – 将一个元素放入队列的尾部。
- pop() – 从队列首部移除元素。
- peek() – 返回队列首部的元素。
- empty() – 返回队列是否为空。
MyQueue queue = new MyQueue();
queue.push(1);
queue.push(2);
queue.peek(); // 返回 1
queue.pop(); // 返回 1
queue.empty(); // 返回 false
本题只能够使用栈的方式模拟队列。栈在Python中是用列表模拟的。所以是用一个列表完成这个操作。这里我们使用两个列表 in_list 和 out_list
.
- 如果有新元素进入,则将该元素存储在
in_list
。 - 如果要删除一个元素,则将
in_list
里的所有元素pop()
出来,然后append()
到out_list
中。完成这个操作后,in_list
中所有元素反转过来了。随后使用outlist.pop()
返回删除的元素. - 如果要查看队列首元素,则先使用
self.pop()
返回队列首的元素。然后把这个元素在append()
到out_list
中,因为peek()
不删除元素。 empty()
就是如果in_list和out_list
没有元素
代码实现:
class MyQueue(object):
def __init__(self):
self.in_stack = []
self.out_stack = []
def push(self, x):
"""
:type x: int
:rtype: None
"""
self.in_stack.append(x)
def pop(self):
"""
:rtype: int
"""
if self.empty():
return None
if len(self.out_stack)==0:
for i in range(len(self.in_stack)-1):
self.out_stack.append(self.in_stack.pop())
return self.in_stack.pop()
if len(self.out_stack)!=0:
return self.out_stack.pop()
def peek(self):
"""
:rtype: int
"""
temp = self.pop()
self.out_stack.append(temp)
return temp
def empty(self):
"""
:rtype: bool
"""
return len(self.in_stack)==0 and len(self.out_stack)==0
# 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()
用队列实现栈
使用队列实现栈的下列操作:
- push(x) – 元素 x 入栈
- pop() – 移除栈顶元素
- top() – 获取栈顶元素
- empty() – 返回栈是否为空
这道题在Python使用一个deque()实现。`que = deque()
- 增加元素的时候使用
que.append()
添加在队伍中 - 删除元素时需要删除最后一个进入队列的元素。但是由于队列只能够返回最先进入队列的元素,则需要整体循环一次队列,将每个元素都
popleft()
出来,再append()
回去,直到最后一个元素被删除。队伍顺序由于队首先删除,随即添加到队尾,所以顺序没改变 - 获取栈顶元素与删除元素一样,只是最后要把最后一个元素返回到队列中,因为只是查看
- 判断是否为空,只需要判断
len(que)==0
代码实现:
class MyStack(object):
def __init__(self):
self.que = deque()
def push(self, x):
"""
:type x: int
:rtype: None
"""
self.que.append(x)
def pop(self):
"""
:rtype: int
"""
if self.empty():
return None
for i in range(len(self.que)-1):
self.que.append(self.que.popleft())
return self.que.popleft()
def top(self):
"""
:rtype: int
"""
"""
# 另一种写法:
if self.empty():
return None
return self.que[-1]
"""
if self.empty():
return None
for i in range(len(self.que)-1):
self.que.append(self.que.popleft())
temp = self.que.popleft()
self.que.append(temp)
return temp
def empty(self):
"""
:rtype: bool
"""
return len(self.que) == 0
# Your MyStack object will be instantiated and called as such:
# obj = MyStack()
# obj.push(x)
# param_2 = obj.pop()
# param_3 = obj.top()
# param_4 = obj.empty()
总结:
队列和栈,基础数据结构!