栈和队列(python)
栈:
1.First In Last Out(FILO)
2.先进后出,后进先出(桶/弹夹等)
python实现栈:
class Stack(object): def __init__(self): self.stack = [] def pop(self): if self.is_empty(): return None else: return self.stack.pop() def push(self,val): return self.stack.append(val) def peak(self): if self.is_empty(): return None else: return self.stack[-1] def size(self): return len(self.stack) def is_empty(self): return self.size() == 0 s = Stack() s.push(1) s.peak() s.is_empty() s.pop()
队列:
1.First In First Out(FIFO)
2.先进先出
python实现:
class Queue(object):
def __init__(self):
self.queue = []
def enqueue(self,val):
self.queue.insert(0,val)
def dequeue(self):
if self.is_empty():
return None
else:
return self.queue.pop()
def size(self):
return len(self.queue)
def is_empty(self):
return self.size() == 0
q = Queue()
q.enqueue(1)
q.is_empty()
q.dequeue()
需求:使用队列模拟栈/使用栈模拟队列
1.使用一个队列模拟栈:
class StackByQueue(object): def __init__(self): self.queue = Queue() def push(self, val): self.queue.enqueue(val) def pop(self): for i in range(self.queue.size() - 1): value = self.queue.dequeue() self.queue.enqueue(value) return self.queue.dequeue()
2.使用两个栈模拟队列:
class QueueByStack(object):
def __init__(self):
self.stack1 = Stack()
self.stack2 = Stack()
def enqueue(self, val):
self.stack1.push(val)
def dequeue(self):
for i in range(self.stack1.size() - 1):
value = self.stack1.pop()
self.stack2.push(value)
res = self.stack1.pop()
for i in range(self.stack2.size()):
value = self.stack2.pop()
self.stack1.push(value)
return res