在python的链表中的第N个位置插入一个节点

时间:2017-09-21 17:50:18

标签: python python-2.7 linked-list nodes

我正在尝试插入节点" item"在位置"索引"在链接列表中,我有以下代码,对我来说听起来不错,但它无法正常工作。

如果有人可以帮助我,我真的很感激。

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

    def getData(self):
        return self.data

    def getNext(self):
        return self.next

    def setData(self,newdata):
        self.data = newdata

    def setNext(self,newnext):
        self.next = newnext

然后我有:

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

    def isEmpty(self):
        return self.head ==None

    def add(self,newdata):
        Temp = Node(newdata)
        #         What happens here: the Temp.Next is going to connect to the place that head is connected to
        Temp.setNext(self.head)
        self.head = Temp


    def printl(self):
        current = self.head
        i=""
        while current.getNext() != None:
            i =i+ "-"+str(current.getData())
            current= current.getNext()
        i =i+ "-"+str(current.getData())
        return i

    def insert(self,item,index):
        current = self.head
        counter = 0
        Temp = Node(item)

        Prev = None

        if index == 0:
            Temp.setNext(self.head)
            self.head = Temp
        else:
            while counter < index:
                Prev = current
                current = current.getNext()
                counter = counter + 1

                Temp.setNext(Prev.getNext())
                Prev.setNext(Temp.getNext())
                current.setData = Temp

所以我在这里做一些测试:

mylist = UnorderedList()
mylist.insert(54,0)
mylist.add(31)
mylist.add(77)
mylist.add(17)
mylist.add(93)
mylist.add(26)
print(mylist.printl())
mylist.insert(12,2)
print(mylist.printl())

输出是:

-26-93-17-77-31-54
-26-93-17-77-31-54

如您所见,未添加节点。 你能否告诉我我的代码有什么问题以及如何修复它?

1 个答案:

答案 0 :(得分:2)

insert功能上,它应为Prev.setNext(Temp),之前为&#39;接下来必须是要插入的,而不是下一个:

    def insert(self,item,index):
        current = self.head
        counter = 0
        Temp = Node(item)

        Prev = None

        if index == 0:
            Temp.setNext(self.head)
            self.head = Temp
        else:
            while counter < index:
                Prev = current
                current = current.getNext()
                counter = counter + 1

            Temp.setNext(Prev.getNext())
            Prev.setNext(Temp)
            current.setData = Temp