# Python 实现数据结构中的的栈队列

```
# -*- coding: utf-8 -*-
class Stack(object):
"""栈的实现类"""
def __init__(self):
self.__items = []
# push(item) 添加一个新的元素item到栈顶
def push(self, item):
self.__items.append(item)
# pop() 弹出栈顶元素
def pop(self):
return self.__items.pop()
# peek() 返回栈顶元素
def peek(self):
return self.__items[self.size() - 1]
# is_empty() 判断栈是否为空
def is_empty(self):
return self.__items == []
# size() 返回栈的元素个数
def size(self):
return len(self.__items)
if __name__ == '__main__':
stack = Stack()
stack.push(2)
stack.push(3)
stack.push(4)
stack.push(5)
tmp = stack.pop()
print(tmp)
print(stack.peek())
print(stack.size())
print(stack.is_empty())
```

```
# -*- coding: utf-8 -*-
class Queue(object):
"""队列的实现"""
def __init__(self):
self.__items = []
# push(item) 往队列中添加一个item元素
def push(self, item):
self.__items.insert(0, item)
# pop() 从队列头部删除一个元素
def pop(self):
return self.__items.pop()
# is_empty() 判断一个队列是否为空
def is_empty(self):
return self.__items == []
# size() 返回队列的大小
def size(self):
return len(self.__items)
if __name__ == '__main__':
queue = Queue()
queue.push(1)
queue.push(2)
queue.push(3)
queue.push(4)
print(queue.pop())
print(queue.pop())
print(queue.pop())
print(queue.size())
print(queue.is_empty())
```

```
# -*- coding: utf-8 -*-
class Deque(object):
"""双端队列"""
def __init__(self):
self.__items = []
self.__items.insert(0, item)
self.__items.append(item)
# remove_front() 从队头删除一个item元素
def remove_front(self):
return self.__items.pop(0)
# remove_rear() 从队尾删除一个item元素
def remove_rear(self):
return self.__items.pop()
# is_empty() 判断双端队列是否为空
def is_empty(self):
return self.__items == []
# size() 返回队列的大小
def size(self):
return len(self.__items)
def print_items(self):
print(self.__items)
if __name__ == '__main__':
deque = Deque()
deque.print_items()
deque.print_items()
print(deque.is_empty())
print(deque.remove_front())
print(deque.remove_rear())
deque.print_items()
```

QQ号联系： 360901061

【本文对您有帮助就好】