I am trying to understand why does inserting the same node twice in a singly linked list causes an infinite loop.
I tried to insert the last node as the new head node. But when I run the code, it's starting an infinite loop I can see since I am calling a method to print nodes at the end. Here's my code.
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def insertLast(self, newNode):
if self.head is None:
self.head = newNode
else:
lastNode = self.head
while True:
if lastNode.next is None:
break
lastNode = lastNode.next
lastNode.next = newNode
def insertHead(self, newNode):
# x, y ,z. => new head, x,y,z
if self.head is None:
print("List is empy please call inserlast()")
else:
currentHead = self.head
self.head = newNode
self.head.next = currentHead
def printList(self):
if self.head is None:
print("EMPTY List. No Data found!")
return
else:
currentNode = self.head
while True:
print(currentNode.data)
currentNode = currentNode.next
if currentNode is None:
break
node1 = Node("Head")
node2 = Node("Some Data")
node3 = Node("Some More Data")
# I am adding this node at the end of the list
newnode1 = Node("New Head")
linkedList = LinkedList()
# create a new linked list by inserting at end
linkedList.insertLast(node1)
linkedList.insertLast(node2)
linkedList.insertLast(newnode1)
# using a node i have already added in the list as New head of the list
linkedList.insertHead(newnode1)
linkedList.printList()