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

如何在类似结构的链表中插入新节点?另一个

问答内容是:如何在类似结构的链表中删除指定节点?

在类似结构的链表中插入新节点的步骤如下:

  1. 创建一个新节点,并为其赋值。
  2. 找到要插入位置的前一个节点。
  3. 将新节点的next指针指向前一个节点的next指针所指向的节点。
  4. 将前一个节点的next指针指向新节点。

以下是一个示例代码:

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

class LinkedList:
    def __init__(self):
        self.head = None

    def insert(self, data, position):
        new_node = Node(data)

        if position == 0:
            new_node.next = self.head
            self.head = new_node
        else:
            current = self.head
            for _ in range(position - 1):
                if current.next is None:
                    raise IndexError("Position out of range")
                current = current.next

            new_node.next = current.next
            current.next = new_node

    def display(self):
        current = self.head
        while current:
            print(current.data, end=" ")
            current = current.next
        print()

# 创建链表
linked_list = LinkedList()

# 插入节点
linked_list.insert(1, 0)  # 在位置0插入节点1
linked_list.insert(2, 1)  # 在位置1插入节点2
linked_list.insert(3, 2)  # 在位置2插入节点3

# 显示链表
linked_list.display()  # 输出:1 2 3

在类似结构的链表中删除指定节点的步骤如下:

  1. 找到要删除节点的前一个节点。
  2. 将前一个节点的next指针指向要删除节点的下一个节点。

以下是一个示例代码:

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

class LinkedList:
    def __init__(self):
        self.head = None

    def delete(self, position):
        if self.head is None:
            raise IndexError("List is empty")

        if position == 0:
            self.head = self.head.next
        else:
            current = self.head
            for _ in range(position - 1):
                if current.next is None:
                    raise IndexError("Position out of range")
                current = current.next

            if current.next is None:
                raise IndexError("Position out of range")

            current.next = current.next.next

    def display(self):
        current = self.head
        while current:
            print(current.data, end=" ")
            current = current.next
        print()

# 创建链表
linked_list = LinkedList()

# 插入节点
linked_list.insert(1, 0)  # 在位置0插入节点1
linked_list.insert(2, 1)  # 在位置1插入节点2
linked_list.insert(3, 2)  # 在位置2插入节点3

# 删除节点
linked_list.delete(1)  # 删除位置1的节点

# 显示链表
linked_list.display()  # 输出:1 3

这是一个基本的链表插入和删除操作的实现。链表是一种常见的数据结构,适用于需要频繁插入和删除节点的场景,比如实现队列、栈等数据结构,或者用于解决一些特定的问题。

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

相关·内容

1时29分

企业出海秘籍:如何以「稳定」产品提升留存,以AIGC「创新」实现全球增长?

1时8分

TDSQL安装部署实战

16分8秒

人工智能新途-用路由器集群模仿神经元集群

领券