在Python中的链表的开头插入节点

2024-09-30 18:31:17 发布

您现在位置:Python中文网/ 问答频道 /正文

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.


Tags: theinnonedataisdefcountnot
1条回答
网友
1楼 · 发布于 2024-09-30 18:31:17

您需要用insertAtI返回的头覆盖head变量。如果使用insertAtI(head, 0, <whatever>)插入到列表的开头,它将返回一个新元素作为head;如果在列表的其他地方插入,它将返回您传入的相同head。所以不是

insertAtI(head, 1, 7)
insertAtI(head, 4, 9)
insertAtI(head, 0, 2)
printLL(head)

head = insertAtI(head, 1, 7)
head = insertAtI(head, 4, 9)
head = insertAtI(head, 0, 2)
printLL(head)

相关问题 更多 >