Python-单链表实现队列

class Node:
    """初始化链表"""
    def __init__(self, val):
        self.val = val
        self.next = None

class linkQueue:
    def __init__(self):
        self.dummyhead = Node(None) #哑结点,哑结点的下一个结点就是表头front
        self.rear = self.dummyhead

    def enQueue(self, item):
        '''插入到表尾'''
        if not isinstance(item,Node):item = Node(item)
        if self.isEmpty():
            self.dummyhead.next = item
        else:
            self.rear.next = item
        self.rear = item
        return self.dummyhead.next

    def deQueue(self):
        '''删除并返回表头元素'''
        if self.isEmpty():
            raise Exception('队列空')
        elif self.rear == self.dummyhead.next:
            data = self.dummyhead.next.val
            self.dummyhead.next = self.dummyhead.next.next
            return data
        else:
            data = self.dummyhead.next.val
            self.dummyhead.next = self.dummyhead.next.next
            return data

    def isEmpty(self):
        return self.dummyhead.next == None

    def printQueue(self):
        """
        循环打印链表中的每个值
        :return:
        """
        currnode = self.dummyhead.next
        if not currnode:raise Exception('队列空')
        while currnode:
            print(currnode.val)
            currnode = currnode.next

if __name__ == '__main__':
    queue = linkQueue()
    print(queue.isEmpty())
    # queue.deQueue()
    queue.enQueue(1)
    queue.enQueue(2)
    queue.enQueue(3)
    queue.deQueue()
    queue.printQueue()

 

你可能感兴趣的:(数据结构,Python,python,单链表,队列,数据结构)