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.
您需要用
insertAtI
返回的头覆盖head
变量。如果使用insertAtI(head, 0, <whatever>)
插入到列表的开头,它将返回一个新元素作为head;如果在列表的其他地方插入,它将返回您传入的相同head。所以不是做
相关问题 更多 >
编程相关推荐