#Creates a new Node
#nextnode acts as a pointer
class Node(object):
def __init__(self,data):
self.data = data
self.nextnode = None
class LinkedList(object):
def __init__(self):
self.head = None
self.size =0
#Insertion
Adding elements at start and end of linked list
def insertStart(self,data):
self.size+=1
newnode = Node(data)
if not self.head:
self.head = newnode
else:
newnode.nextnode = self.head
self.head = newnode
def size(self):
return self.size
def insertEnd(self,data):
self.size+=1
newnode = Node(data)
actualnode = self.head
while actualnode is not None:
actualnode = actualnode.nextnode #Eroor here!!!!
actualnode.nextnode = newnode
#Traversing through linked list
def traverse(self):
actualnode = self.head
while actualnode is not None:
print("Actual Node {}".format(actualnode.data))
actualnode = actualnode.nextnode
#Removing node
def remove(self,data):
if (self.head == None):
return
currentnode = self.head
previousnode = None
while (currentnode.data != data):
previousnode = currentnode
currentnode = currentnode.nextnode
if previousnode is None:
self.head = currentnode.nextnode
else:
previousnode.nextnode = currentnode.nextnode
linkedlist = LinkedList()
linkedlist.insertStart(12)
linkedlist.insertStart(13)
linkedlist.insertStart(14)
linkedlist.insertStart(15)
linkedlist.insertEnd(16)
linkedlist.traverse()
答案 0 :(得分:0)
在insertEnd
中,您保证在循环结束时始终None
为actualnode
:
def insertEnd(self, data):
self.size += 1
newnode = Node(data)
actualnode = self.head
# Keep going until actualnode is None
while actualnode is not None:
actualnode = actualnode.nextnode
# Here actualnode will always be None
actualnode.nextnode = newnode
要解决此问题,只需更改while循环条件:
while actualnode.nextnode is not None:
actualnode = actualnode.nextnode
请注意,这假定self.head
始终为非None
。您应该明确检查这种情况。也许是这样的:
def insertEnd(self, data):
self.size += 1
newnode = Node(data)
if self.head is None:
self.head = newnode
else:
actualnode = self.head
while actualnode.nextnode is not None:
actualnode = actualnode.nextnode
actualnode.nextnode = newnode