1. 队列
class Queue(object):
""" list实现队列(左进右出) """
def __init__(self):
self._list = []
def push(self, item):
""" 在队尾插入元素 """
self._list.insert(0, item)
def pop(self):
""" 删除并获取队首元素 """
return self._list.pop()
def size(self):
""" 返回队列的大小 """
return len(self._list)
def clear(self):
""" 清空队列 """
self._list.clear()
def is_empty(self):
""" 判断队列是否为空 """
return self._list == []
def items(self):
""" 返回队列中的所有元素 """
return self._list
if __name__ == "__main__":
q = Queue()
print(q.items())
q.push(1)
print(q.items())
q.push(2)
print(q.items())
q.push(3)
print(q.items())
q.push(4)
print(q.items())
q.pop()
print(q.items())
q.pop()
print(q.items())
print(q.is_empty())
print(q.size())
q.clear()
print(q.items())
print(q.is_empty())
class Queue(object):
""" list实现队列(右进左出) """
def __init__(self):
self._list = []
def push(self, item):
""" 在队尾插入元素 """
self._list.append(item)
def pop(self):
""" 删除并获取队首元素 """
return self._list.pop(0)
def size(self):
""" 返回队列的大小 """
return len(self._list)
def clear(self):
""" 清空队列 """
self._list.clear()
def is_empty(self):
""" 判断队列是否为空 """
return self._list == []
def items(self):
""" 返回队列中的所有元素 """
return self._list
if __name__ == "__main__":
q = Queue()
print(q.items())
q.push(1)
print(q.items())
q.push(2)
print(q.items())
q.push(3)
print(q.items())
q.push(4)
print(q.items())
q.pop()
print(q.items())
q.pop()
print(q.items())
print(q.is_empty())
print(q.size())
q.clear()
print(q.items())
print(q.is_empty())
2. 双端队列
class DQueue(object):
""" list实现双端队列 """
def __init__(self):
self._list = []
def lpush(self, item):
""" 在列左侧插入元素 """
self._list.insert(0, item)
def rpush(self, item):
""" 在队列右侧插入元素 """
self._list.append(item)
def lpop(self):
""" 删除并获取队列左侧第一个元素 """
return self._list.pop(0)
def rpop(self):
""" 删除并获取队列右侧第一个元素 """
return self._list.pop()
def size(self):
""" 返回队列的大小 """
return len(self._list)
def clear(self):
""" 清空队列 """
self._list.clear()
def is_empty(self):
""" 判断队列是否为空 """
return self._list == []
def items(self):
""" 返回队列中的所有元素 """
return self._list
if __name__ == "__main__":
q = DQueue()
print(q.items())
q.lpush(1)
print(q.items())
q.lpush(2)
print(q.items())
q.rpush(3)
print(q.items())
q.rpush(4)
print(q.items())
q.lpop()
print(q.items())
q.rpop()
print(q.items())
print(q.is_empty())
print(q.size())
q.clear()
print(q.items())
print(q.is_empty())
Reference
[1]: https://www.cnblogs.com/Wu13241454771/p/13691513.html
[2]: https://blog.csdn.net/sixkery/article/details/83149599