You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

HackerRank链表节点删除问题:单个测试用例失败需排查

链表节点删除功能错误排查

我在完成链表节点删除的编程挑战时,遇到一个测试用例始终无法通过。测试用例输入如下:

7
11
12
8
18
16
5
18
0

预期输出是 12 8 18 16 5 18,但当前代码无法得到正确结果。

当前代码如下:

#!/bin/python3

import math
import os
import random
import re
import sys

class SinglyLinkedListNode:
    def __init__(self, node_data):
        self.data = node_data
        self.next = None

class SinglyLinkedList:
    def __init__(self):
        self.head = None
        self.tail = None

    def insert_node(self, node_data):
        node = SinglyLinkedListNode(node_data)

        if not self.head:
            self.head = node
        else:
            self.tail.next = node

        self.tail = node

def print_singly_linked_list(node, sep, fptr):
    while node:
        fptr.write(str(node.data))

        node = node.next

        if node:
            fptr.write(sep)

#
# Complete the 'deleteNode' function below.
#
# The function is expected to return an INTEGER_SINGLY_LINKED_LIST.
# The function accepts following parameters:
#  1. INTEGER_SINGLY_LINKED_LIST llist
#  2. INTEGER position
#

#
# For your reference:
#
# SinglyLinkedListNode:
#     int data
#     SinglyLinkedListNode next
#
#

def deleteNode(llist, position):
    # Write your code here
    if llist is None: 
        llist=None
        return llist
    else:
        temp=llist
        index=0
        while index<position-1:
            temp=temp.next
            index+=1
        new_node=temp.next
        temp.next=new_node.next 
            
    return llist
            
        

if __name__ == '__main__':
    fptr = open(os.environ['OUTPUT_PATH'], 'w')

    llist_count = int(input())

    llist = SinglyLinkedList()

    for _ in range(llist_count):
        llist_item = int(input())
        llist.insert_node(llist_item)

    position = int(input())

    llist1 = deleteNode(llist.head, position)

    print_singly_linked_list(llist1, ' ', fptr)
    fptr.write('\n')

    fptr.close()

错误原因分析

你的代码存在一个关键问题:没有处理删除头节点(position=0)的情况。
当position为0时,代码里的while循环条件index < position-1即index < -1,循环根本不会执行。此时temp还是原头节点,代码执行temp.next = new_node.next(这里new_node是temp.next也就是第二个节点),但最后返回的还是原来的llist(原头节点),这就导致头节点没有被删除,输出结果仍然包含11,和预期不符。

修正后的代码

修改deleteNode函数如下:

def deleteNode(llist, position):
    # 处理空链表情况
    if llist is None: 
        return None
    # 处理删除头节点的情况
    if position == 0:
        return llist.next
    # 处理其他位置的删除
    temp = llist
    index = 0
    # 找到要删除节点的前一个节点
    while index < position - 1:
        temp = temp.next
        index += 1
    # 跳过要删除的节点,同时避免空指针异常
    if temp.next is not None:
        temp.next = temp.next.next
    return llist

修正说明

  1. 新增position=0的判断,直接返回原头节点的next作为新的头节点,完成头节点删除。
  2. 增加了对temp.next是否为空的判断,避免链表越界(比如删除最后一个节点时的情况)。

内容的提问来源于stack exchange,提问作者JG1

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 11:35:04