【问题标题】:How to insert value in single linked list after a certain value?如何在某个值之后在单链表中插入值?
【发布时间】:2020-06-25 11:35:09
【问题描述】:

这是我的代码 sn-p 用于完成上面标题中的任务:

def insert_Position(self, value, pos):
    new_node = Node(value)
    temp = self.head
    while temp.data == pos:
        temp = temp.next
    new_node.next = temp.next
    temp.next = new_node

我想在值 40 之后插入值 45 但我得到了这样的输出

10 20 30 40 50

10 45 20 30 40 50

pos 包含我要插入新值的值。

我想要这样的输出:

10 20 30 40 45 50

【问题讨论】:

  • 您需要管理指针,使它们处于所需的顺序
  • 您的意思是:while temp.data != pos:
  • btw 你能用Node的定义更新你的问题吗?
  • 感谢 quamrana 哥们我得到了答案
  • 顺便说一句,不要纠正你的问题,否则数百万未来的程序员将无法找到这个问题。

标签: python list linked-list


【解决方案1】:

while循环条件不正确。

def insert_Position(self, value, pos):
    new_node = Node(value)
    temp = self.head
    while temp <= pos:
        temp = temp.next
    new_node.next = temp.next
    temp.next = new_node

【讨论】:

    猜你喜欢
    • 2019-12-11
    • 1970-01-01
    • 1970-01-01
    • 2022-11-24
    • 2017-10-15
    • 2020-07-02
    • 1970-01-01
    • 2020-10-13
    • 1970-01-01
    相关资源
    最近更新 更多