python-栈-队列-双端队列
2021-02-05 本文已影响0人
涓涓自然卷
- 1、栈:先进后出
# 尾部插入删除数据
# append(item), pop()
class Stack(object):
"""栈:先进后出"""
def __init__(self):
self.__items = []
def push(self, item):
"""进栈"""
self.__items.append(item)
def pop(self):
"""出栈"""
self.__items.pop()
def travel(self):
"""遍历"""
for i in self.__items:
print(i)
# 进栈
print("进栈结果:")
my_stack = Stack()
my_stack.push(1)
my_stack.push(2)
my_stack.push(3)
my_stack.travel()
# 出栈
print("出栈后的结果:")
my_stack.pop()
my_stack.travel()
- 运行结果:
- 2、队列:先进先出
# Queue()
# 创建一个空的队列items
class Queue(object):
def __init__(self):
# 存储数据,线性表
self.items = []
# enqueue():
# 队列尾部添加元素item
def enqueue(self, item):
self.items.append(item)
# dequeue():
# 队列头部删除元素
def dequeue(self):
self.items.pop(0)
# is_empty()
# 判断队列是否为空
def is_empty(self):
return self.items == []
# size()
# 返回队列的大小
def size(self):
return len(self.items)
q = Queue()
# 添加数据
q.enqueue(1)
q.enqueue(2)
q.enqueue(3)
print("添加数据结果:")
for i in q.items:
print(i)
# 删除数据
q.dequeue()
print("删除数据结果:")
for i in q.items:
print(i)
print("是否为空结果:")
print(q.is_empty())
print("列表长度结果:")
print(q.size())
- 运行结果:
- 3、双端队列:
class Deque(object):
"""双端队列"""
def __init__(self):
self.items = []
def is_empty(self):
"""判断是否为空"""
return self.items == []
def size(self):
"""返回队列大小"""
return len(self.items)
def add_front(self, item):
"""头部添加数据"""
self.items.insert(0, item)
def add_rear(self, item):
"""尾部添加数据"""
self.items.append(item)
def remove_front(self):
"""头部删除数据"""
self.items.pop(0)
def remove_rear(self):
"""尾部删除数据"""
self.items.pop()
deque = Deque()
print('队列是否为空:', deque.is_empty())
print('队列长度:', deque.size())
# 添加数据
print("添加数据:")
deque.add_front(1)
deque.add_front(2)
deque.add_rear(3)
deque.add_rear(4)
for i in deque.items:
print(i)
# 删除数据
print("删除尾部数据:")
deque.remove_front()
deque.remove_rear()
for i in deque.items:
print(i)
- 运行结果: