I am trying to insert a node "item" in position "index" in a linked list, I have the following code and to me it sounds fine, but it is not working right.
I would really appreciate if someone can help me out.
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
And then I have:
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
So here I do some test:
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())
And the output is:
-26-93-17-77-31-54
-26-93-17-77-31-54
As you can see the node is not added. Can you please tell me what is wrong with my code and how I can fix it?
On the insert
function, it should be Prev.setNext(Temp)
, previous' next have to be the one to be inserted, not its next:
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.