Python链表实现-在第n个位置插入节点?为什么代码不起作用?

问题描述 投票:0回答:1

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   
python algorithm data-structures linked-list singly-linked-list
1个回答
0
投票
您可以在下面假设第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

© www.soinside.com 2019 - 2024. All rights reserved.