线性结构的python实现(二:双向链表和双向循环链表)

以下为双向链表和双向循环链表的python实现:

class Node():
    """双向链表节点类,包含链表基本操作。"""
    def __init__(self, value):
        self.value = value
        self.next = None
        self.pre = None  # 指向前一个节点的指针

    def __str__(self):
        return str(self.value)

    def each(self, number=float('inf'), reverse=False):
        """
        遍历链表并输出值
        :param number: 输出数量,默认全部输出
        :param reverse: 控制遍历方向,默认为正向遍历;如果为 True,则反向遍历
        :return:None
        """
        node = self
        while node is not None and number:
            print(node, end=' ')
            node = node.pre if reverse else node.next  # 根据reverse的值向前或向后移动
            number -= 1
        print('\n')


class DoublyLinkedList():
    """双向链表类,提供了初始化、从左右添加元素、从左右弹出元素、以及正反序遍历链表的基本操作。"""
    def __init__(self, data_list):
        self.head = Node(data_list[0])
        pre_node = self.head
        for data in data_list[1:]:
            node = Node(data)
            pre_node.next = node
            node.pre = pre_node
            pre_node = node
        self.end = pre_node

    def add(self, data):
        node = Node(data)
        self.end.next = node
        node.pre = self.end
        self.end = node

    def add_left(self, data):
        node = Node(data)
        node.next = self.head
        self.head.pre = node
        self.head = node

    def pop(self):
        return_data = self.end
        self.end = self.end.pre
        self.end.next = None
        return return_data

    def pop_left(self):
        return_data = self.head
        self.head = self.head.next
        self.head.pre = None
        return return_data

    def each(self, reverse=False):
        self.end.each(reverse=True) if reverse else self.head.each()


def circular_decorator(func):
    # 循环装饰器,用于确保在执行特定方法后双向链表保持循环状态
    def wrapper(self, *args, **kwargs):
        return_value = func(self, *args, **kwargs)
        self.end.next = self.head
        self.head.pre = self.end
        return return_value
    return wrapper

class DoublyLinkedCircularList(DoublyLinkedList):
    """双向循环链表"""
    @circular_decorator
    def __init__(self, data_list):
        super().__init__(data_list)

    @circular_decorator
    def add(self, data):
        super().add(data)

    @circular_decorator
    def add_left(self, data):
        super().add_left(data)

    @circular_decorator
    def pop(self):
        return super().pop()

    @circular_decorator
    def pop_left(self):
        return super().pop_left()

    def each(self, reverse=False):
        self.end.each(10, True) if reverse else self.head.each(10)


if __name__ == '__main__':
    def print_format(obj):
        print('链表:');obj.each()
        print('反向链表:');obj.each(reverse=True)
        obj.add(4);obj.add_left(0)
        print('起始添加0、末尾添加4后的链表:');obj.each()
        print(f'弹出起始值:{obj.pop_left()} 弹出末尾值:{obj.pop()} ')
        print('弹出后的链表:');obj.each()

    print_format(DoublyLinkedList([1, 2, 3]))
    print_format(DoublyLinkedCircularList([1, 2, 3]))

输出:

链表:
1 2 3 

反向链表:
3 2 1 

起始添加0、末尾添加4后的链表:
0 1 2 3 4 

弹出起始值:0 弹出末尾值:4 
弹出后的链表:
1 2 3 

链表:
1 2 3 1 2 3 1 2 3 1 

反向链表:
3 2 1 3 2 1 3 2 1 3 

起始添加0、末尾添加4后的链表:
0 1 2 3 4 0 1 2 3 4 

弹出起始值:0 弹出末尾值:4 
弹出后的链表:
1 2 3 1 2 3 1 2 3 1 

你可能感兴趣的:(python,算法,数据结构,链表)