栈
![](https://i-blog.csdnimg.cn/blog_migrate/5e60e4e9a829d6f4b101f1f28bf2fa38.png)
队列
![](https://i-blog.csdnimg.cn/blog_migrate/499026ac9f73e5d7b621841fb1dbb1d3.png)
栈的实现
![](https://i-blog.csdnimg.cn/blog_migrate/9422819428483cf4fa16828055dc776a.png)
顺序表实现
class Stack(object):
"""栈"""
def __init__(self):
self.__list = [] # 选用顺序表或链表
def push(self,item):
"""压栈"""
self.__list.append(item) # 时间复杂度O(1)
self.__list.insert(0,item) #头部插入,时间复杂度O(n)
# 说明:链表结构的话,头部插入。
def pop(self):
return self.__list.pop()
# return self.__list[0] #时间复杂度 O(n)
def peek(self):
"""返回栈顶元素"""
if self.__list: #不为空
return self.__list[-1]
else:
return None
def is_empty(self):
"""是否为空"""
return not self.__list
def size(self):
return len(self.__list)
if __name__ == '__main__':
s = Stack()
s.push(1)
s.push(3)
s.push(4)
s.push(5)
s.push(6)
print(s.pop())
print(s.pop())
print(s.pop())
print(s.pop())
换个姿势,链表实现 队列
import queue
class Node(object):
def __init__(self,item):
self.item = item
self.next = None
class Queue(object):
"""队列"""
def __init__(self,node=None):
self._head = node
def enqueue(self,item):
"""入队"""
node = Node(item)
node.next = self._head
self._head = node
def dequeue(self):
"""出队"""
cur = self._head
pre = None
while cur.next!= None:
pre = cur
cur = cur.next
if cur is self._head:
self._head = cur.next
return cur.item
pre.next = None
return cur.item
def is_empty(self):
"""判断是否为空"""
return self._head == None
def size(self):
cur = self._head
index = 0
while cur!= None:
cur = cur.next
index+=1
return index
双端队列
![](https://i-blog.csdnimg.cn/blog_migrate/4891618bc8f17372fde9bd90f9f726ee.png)
操作:
#encoding:utf-8
# __author__ = 'donghao'
# __time__ = 2019/3/16 17:17
class Deque(object):
def __init__(self):
self._list = []
def add_front(self,item):
self._list.insert(0,item)
def add_end(self,item):
self._list.append(item)
def pop_front(self):
return self._list.pop(0)
def pop_end(self):
return self._list.pop()
def size(self):
return len(self._list)
def is_empty(self):
return self._list == []
if __name__ == '__main__':
que = Deque()
que.add_end(1)
que.add_end(2) # [6,5,4,1,2,3]
que.add_end(3)
que.add_front(4)
que.add_front(5)
que.add_front(6)
print(que.pop_front())
print(que.pop_end())
print(que.pop_end())
print(que.pop_end())