首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

如何创建一个哑头双循环链表python?

哑头双循环链表是一种特殊的链表数据结构,它在普通双循环链表的基础上添加了一个哑头节点,用于简化链表操作。下面是创建一个哑头双循环链表的Python代码示例:

代码语言:txt
复制
class Node:
    def __init__(self, data=None):
        self.data = data
        self.prev = None
        self.next = None

class DummyHeadDoubleLinkedList:
    def __init__(self):
        self.dummy_head = Node()  # 哑头节点
        self.dummy_head.prev = self.dummy_head
        self.dummy_head.next = self.dummy_head

    def is_empty(self):
        return self.dummy_head.next == self.dummy_head

    def add_node(self, data):
        new_node = Node(data)
        new_node.prev = self.dummy_head
        new_node.next = self.dummy_head.next
        self.dummy_head.next.prev = new_node
        self.dummy_head.next = new_node

    def remove_node(self, data):
        current = self.dummy_head.next
        while current != self.dummy_head:
            if current.data == data:
                current.prev.next = current.next
                current.next.prev = current.prev
                return
            current = current.next

    def print_list(self):
        current = self.dummy_head.next
        while current != self.dummy_head:
            print(current.data, end=" ")
            current = current.next
        print()

# 创建一个哑头双循环链表
dll = DummyHeadDoubleLinkedList()
dll.add_node(1)
dll.add_node(2)
dll.add_node(3)

# 打印链表
dll.print_list()  # 输出: 1 2 3

# 删除节点
dll.remove_node(2)

# 打印链表
dll.print_list()  # 输出: 1 3

这段代码实现了一个哑头双循环链表的基本功能,包括判断链表是否为空、向链表中添加节点、从链表中删除节点以及打印链表内容。你可以根据需要进行扩展和修改。

关于云计算、IT互联网领域的名词词汇,可以参考腾讯云的官方文档和产品介绍页面,其中包含了丰富的云计算相关概念、分类、优势、应用场景以及推荐的腾讯云产品。具体链接地址请参考腾讯云官方网站。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

领券