【数据结构专项】链表(7) —— 管理双向链表的基本类(使用双侧哨兵结点)

class DoublyLinkedBase:
    """管理双向链表的基本类(使用双侧哨兵结点)"""

    class _Node:
        __slots__ = "value", "prev", "next"  # 因为会创建很多个结点对象,因此使用__slots__来减少内存占用

        def __init__(self, value, prev=None, next=None):
            self.value = value
            self.prev = prev
            self.next = next

        def __str__(self):
            return str(self.value) + "<->" + str(self.next)

    def __init__(self):
        self._header = self._Node(None)  # 头部哨兵结点
        self._trailer = self._Node(None)  # 尾部哨兵结点
        self._header.next = self._trailer
        self._trailer.prev = self._header
        self._size = 0

    def __len__(self):
        """返回链表中元素的数量"""
        return self._size

    def is_empty(self):
        """返回链表是否为空"""
        return self._size == 0

    def insert_between(self, value, prev, next):
        """向链表中添加新结点"""
        node = self._Node(value, prev, next)
        prev.next = node
        next.prev = node
        self._size += 1
        return node

    def delete_node(self, node):
        """从链表中删除结点"""
        prev = node.prev
        next = node.next
        prev.next = next
        next.prev = prev
        self._size -= 1
        value = node.value
        node.prev = node.next = node.val = None
        return value

你可能感兴趣的:(数据结构与算法专项,算法,数据结构,链表,数据结构,双向链表,算法)