python学习之双端队列和链表实现队列
Posted 今夜月色很美
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python学习之双端队列和链表实现队列相关的知识,希望对你有一定的参考价值。
一、使用数组实现双端队列
class Deque:
def __init__(self):
self.list = list()
def addFront(self, item):
self.list.insert(0, item)
def addRear(self, item):
self.list.append(item)
def removeFront(self):
return self.list.pop(0)
def removeLast(self):
return self.list.pop()
def size(self):
return len(self.list)
def isEmpty(self):
return self.list == []
def __str__(self):
return self.list.__str__()
二、使用链表实现队列
1.定义链表节点对象node
class Node:
def __init__(self, data):
self.data = data
self.next = None
def getData(self):
return self.data
def getNext(self):
return self.next
def setData(self, data):
self.data = data
def setNext(self, node):
self.next = node
2.使用链表实现队列
from node import Node
class LinkedQueue:
def __init__(self):
self.head = self.last = Node(None)
def offer(self, data):
newNode = Node(data)
newNode.setNext(None)
self.last.setNext(newNode)
self.last = self.last.getNext()
def poll(self):
firstNode = self.head.getNext()
if firstNode == None:
print("队列是空的。")
else:
self.head.setNext(self.head.getNext().getNext())
return firstNode.getData()
3.测试
from linked_queue import LinkedQueue
queue = LinkedQueue()
queue.offer(11)
queue.offer(22)
queue.offer(33)
queue.offer(44)
queue.offer(55)
print(queue.poll())
print(queue.poll())
print(queue.poll())
print(queue.poll())
print(queue.poll())
print(queue.poll())
print(queue.poll())
以上是关于python学习之双端队列和链表实现队列的主要内容,如果未能解决你的问题,请参考以下文章