堆栈:last in first out
队列:first in last out
python中队列的常用操作
# Creating queue
from collections import deque
d = deque()
#Appending to the Right (Tail)
d.append(item)
#Appending to the Left (Head):
d.appendleft(item)
#Popping from the Right (Tail):
item = d.pop()
#Popping from the Left (Head):
item = d.popleft()
#Accessing Elements:
# Accessing the rightmost element
rightmost_item = d[-1]
# Accessing the leftmost element
leftmost_item = d[0]
#hecking if the Deque is Empty:
is_empty = not bool(d)
#Getting the Size of the Deque:
size = len(d)
python中常见的stack操作:
在Python中,通常使用list
来实现栈(stack)。
stack = []
stack.append(item)
item = stack.pop() # 将栈顶部的元素弹出,也就是list的最右一个元素
top_item = stack[-1]
is_empty = not bool(stack)
size = len(stack)
stack.clear()
stack = []
232. Implement Queue using Stacks
Implement a first in first out (FIFO) queue using only two stacks. The implemented queue should support all the functions of a normal queue (push
, peek
, pop
, and empty
).
Implement the MyQueue
class:
void push(int x)
Pushes element x to the back of the queue.int pop()
Removes the element from the front of the queue and returns it.int peek()
Returns the element at the front of the queue.boolean empty()
Returnstrue
if the queue is empty,false
otherwise.
Notes:
- You must use only standard operations of a stack, which means only
push to top
,peek/pop from top
,size
, andis empty
operations are valid. - Depending on your language, the stack may not be supported natively. You may simulate a stack using a list or deque (double-ended queue) as long as you use only a stack's standard operations.
Example 1:
Input ["MyQueue", "push", "push", "peek", "pop", "empty"] [[], [1], [2], [], [], []] Output [null, null, null, 1, 1, false]
思路:用stack来实现queue。stack是后进先出,然如果有两个stack,第一个stack按照后进先出的顺序把元素push进第二个stack中,元素的顺序就变成了后进后出(这里的加粗的后是元素进入第一个stack里“后”的顺序),也就实现了队列,所谓负负得正。。
class MyQueue(object):
def __init__(self):
self.stack_in = [] # for push
self.stack_out = [] # for pop
def push(self, x):
"""
:type x: int
:rtype: None
"""
self.stack_in.append(x)
def pop(self):
"""
:rtype: int
"""
if self.empty(): # In case the "queue" is empty. But it's not necessary to pass the testing sets in leetcode.
return None
if self.stack_out:
return self.stack_out.pop()
else:
for i in range(len(self.stack_in)):
self.stack_out.append(self.stack_in.pop())
return self.stack_out.pop()
def peek(self):
"""
:rtype: int
"""
ans = self.pop() # reuse the self.pop
self.stack_out.append(ans) # add the popped item back to the "queue"
return ans
def empty(self):
"""
:rtype: bool
"""
return not (self.stack_in or self.stack_out)
# 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()
- Time complexity: push and empty are O(1), pop and peek are O(n)
225. Implement Stack using Queues
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()
Returnstrue
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
andis 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 1:
Input ["MyStack", "push", "push", "top", "pop", "empty"] [[], [1], [2], [], [], []] Output [null, null, null, 2, 2, false]
思路:和上一题相反,这里用队列实现栈。借助队列popleft先入先出再append的“循环”特性,把最后入的值挪到队列最top,即最左,也就是stack的top。
for i in range(len(self.que)-1):
self.que.append(self.que.popleft())
return self.que.popleft()
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 not self.empty():
for i in range(len(self.que)-1):
self.que.append(self.que.popleft()) # To pop the nth-in item, remove (popleft) the first n-1 items. Append them to the end of the queue again.
return self.que.popleft()
else:
return None
def top(self):
"""
:rtype: int
"""
if not self.empty():
ans = self.pop()
self.que.append(ans) # 注意!这么写是会报错的:self.que = self.que.append(ans),
#因为append只会就地修改列表而不会返回新列表
return ans
else:
return None
#if self.empty():
# return None
#return self.que[-1]
def empty(self):
"""
:rtype: bool
"""
return not self.que
# 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()
pop and top为O(n),其他为O(1)