# encoding=UTF-8
"""
用循环链表存储实现循环队列类
"""
class CircularQueue:
"""Queue implementation using circularly linked list for storage."""
class _Node:
"""lightweight, nonpublick class for storing a singly linked node."""
__slots__ = '_element', '_next' # streamline memory usage
def __init__(self, element, next): # initialize node's fields
self._element = element # reference to user's element
self._next = next # reference to next node
def __init__(self):
"""Create an empty queue"""
self._tail = None # will represent tail of queue
self._size = 0 # number of queue elements
def __len__(self):
"""Return the number of elements in the queue"""
return self._size
def is_empty(self):
"""Return True if the queue is empty"""
return self._size == 0
def first(self):
"""Return (but do not remove) the element at the front of the queue
Raise Empty exception if the queue of empty
"""
if self.is_empty():
raise Exception('queue is empty')
head = self._tail._next
return head._element
def dequeue(self):
"""Remove and return the first element of the queue (i.e., FIFO)
Raise Empty exception if the queue is empty"""
if self.is_empty():
raise Exception('queue is empty')
oldhead = self._tail._next
if self._size == 1: # removing only element
self._tail = None # queue becomes empty
else:
self._tail._next = oldhead._next # bypass the old head
self._size -= 1
return oldhead._element
def enqueue(self, e):
"""Add an element to the back of queue"""
newest = self._Node(e, None)
if self.is_empty():
newest._next = newest
else:
newest._next = self._tail._next
self._tail._next = newest
self._tail = newest
self._size += 1
def rotate(self):
"""Rotate front element to the back of queue"""
if self._size > 0:
self._tail = self._tail._next
def __str__(self):
arr = []
tail = self._tail._next
for i in range(len(self)): # 循环链表,遍历需要指定循环次数,否则会死循环,只记录最后一个元素的位置
arr.append(tail._element)
tail = tail._next
return str(arr)
if __name__ == '__main__':
cqueue = CircularQueue()
cqueue.enqueue(1)
cqueue.enqueue(2)
cqueue.enqueue(3)
cqueue.enqueue(4)
print(cqueue.first())
print(cqueue)
cqueue.rotate()
print(cqueue)
cqueue.dequeue()
print(cqueue)
输出结果
1
[1, 2, 3, 4]
[2, 3, 4, 1]
[3, 4, 1]