Python Реализация связанного списка - Вставить узел в n-й позиции? Почему код не работает? - PullRequest
0 голосов
/ 04 марта 2020

Кодовое изображение

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   

1 Ответ

0 голосов
/ 04 марта 2020

Вы можете попробовать это ниже, предполагая, что 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
...