python 用循环链表存储实现循环队列类

该博客介绍了一个使用循环链表实现的循环队列类。类包含节点定义、初始化、获取队列长度、判断队列是否为空、获取但不移除队首元素、出队、入队和旋转队列等方法。示例展示了如何创建、操作和打印队列,包括元素的添加、移除和循环移动。
摘要由CSDN通过智能技术生成
# 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]
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值