Below is the code for Linked list...we have takeInput() function which takes the input from the user. Also, we have insertAtI() function that is to insert a node anywhere in the linked list. But it's not inserting at the beginning...please have a look...and help me in resolving the issue.
class Node:
def __init__(self, data):
self.data = data
self.next = None
def takeInput():
inputList = [int(ele) for ele in input().split()]
head = None
tail = None
for ele in inputList:
newNode = Node(ele)
if head is None:
head = newNode
tail = newNode
else:
tail.next = newNode
tail = newNode # or tail = tail.next
return head
def length(head):
count = 0
while head is not None:
head = head.next
count += 1
return count
def insertAtI(head, i, data):
if i < 0 or i > length(head):
return head
count = 0
prev = None
curr = head
while count < i:
prev = curr
curr = curr.next
count += 1
newNode = Node(data)
if prev is not None:
prev.next = newNode
else:
head = newNode
newNode.next = curr
return head
def printLL(head):
while head is not None:
print(head.data, end="->")
head = head.next
print("None")
head = takeInput()
printLL(head)
insertAtI(head, 1, 7)
insertAtI(head, 4, 9)
insertAtI(head, 0, 2)
printLL(head)
This code is not inserting the node at the beginning of my linked list. I think the problem is inside insertAtI() function...please help me in resolving the issue.
insertAtIlooks fine to me. You should try addingbreakpoint()before you call the function and stepping through your code to debug it. Also, in Python, variables and function names should be named usinglowercase_with_underscoresnotcamelCase.insertAtItohead.1->2->3->4->Noneand you doprintLL(head.next.next)it'll print3->4->None. When youinsertAtI(head, 0), it creates a new node, but your variableheadis still pointing to the old head (which is now the second element in the list), so when you pass it toprintLL(head)it's not starting from the new head element you created withinsertAtI(). So any time you useinsertAtIyou need to dohead = insertAtIbecause it returns the correcthead