【问题标题】:Python Linked List Implemention - Inserting node at nth position ? Why the code is not working?Python 链表实现 - 在第 n 个位置插入节点?为什么代码不起作用?
【发布时间】:2020-06-16 19:58:11
【问题描述】:

Code Image

class Node:
    def __init__(self,data):
        self.data = data
        self.address = None

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

    def insert_at_position(self,position,data):
        node = Node(data)
        i = 0 
        temp = self.start
        while(i<position-1 and temp!=None):
            i +=1
            temp = temp.address
        t1 = node
        t1.address = temp
        temp = t1   

【问题讨论】:

  • 你能发布你的完整代码吗?
  • 好吧,temp = t1 将新节点分配给一个临时变量。您需要在插入位置之前更新节点的self.startaddress。您还需要确定当position 大于列表时会发生什么。

标签: python algorithm data-structures linked-list singly-linked-list


【解决方案1】:

假设第 0 个位置是 LinkedList 的头部,您可以尝试以下操作:

def insert_at_nth_pos(self, position, data):

        temp = self.start
        if position == 0:
            new_node = Node(data)
            new_node.address = self.head
            self.head = new_node
            return

        for i in range(1, position-1):
            temp = temp.address

        if temp is None:
            print("Position out of Bounds")
            return 

        if temp.address is None:
            temp.address = Node(data)
        else:
            new_node = Node(data)
            new_node.address = temp.address
            temp.address = new_node

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多