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

自定义LinkedList类指定位置节点删除及额外功能实现求助

链表类实现问题解决方案

一、删除指定位置节点功能的问题修复

你的deleteAtPosition方法存在逻辑冗余且错误的问题:

  1. 额外引入visit和pointer节点,导致代码复杂易出错
  2. 最后一个while循环会触发无限循环(比如position>1时,ctr从1递减永远无法等于position)
  3. 核心逻辑错误:删除节点只需找到目标节点的前一个节点,将其next指向目标节点的next即可,无需多余遍历

修正后的代码:

public void deleteAtPosition(int position){
    if(isEmpty()){
        error_message("The list is empty. Try to add a value.");
        return;
    }
    if(position == 0){
        deleteAtFirst();
        return;
    }
    if(position < 0 || position >= currentSize()){
        error_message("Position is NOT valid.");
        return;
    }
    
    // 找到要删除节点的前一个节点
    LNode prev = head;
    for(int i = 0; i < position - 1; i++){
        prev = prev.next;
    }
    // 跳过要删除的节点
    prev.next = prev.next.next;
    // 若类中维护了size变量,删除后需更新长度
    // size--;
}

代码说明:

  • 简化分支判断,每个分支执行后直接return,减少嵌套层级
  • 通过一次遍历定位目标节点的前驱节点prev,直接修改指针完成删除
  • 注意如果链表类有size成员变量,删除操作后需要同步减1

二、额外功能实现

1. 反转链表

public void reverse(){
    LNode prev = null;
    LNode current = head;
    LNode next = null;
    
    while(current != null){
        next = current.next; // 保存下一个节点
        current.next = prev; // 反转当前节点指针
        prev = current;      // prev指针后移
        current = next;      // current指针后移
    }
    head = prev; // 反转后头节点变为原尾节点
}

2. 查找链表中间节点(快慢指针法)

public LNode findMiddle(){
    if(isEmpty()){
        error_message("The list is empty.");
        return null;
    }
    
    LNode slow = head;
    LNode fast = head;
    
    // 快指针走两步,慢指针走一步,快指针到尾时慢指针处于中间位置
    while(fast != null && fast.next != null){
        slow = slow.next;
        fast = fast.next.next;
    }
    return slow;
}

3. 检测链表是否存在环(快慢指针法)

public boolean hasCycle(){
    if(isEmpty() || head.next == null){
        return false;
    }
    
    LNode slow = head;
    LNode fast = head.next;
    
    // 快慢指针相遇则说明存在环
    while(slow != fast){
        if(fast == null || fast.next == null){
            return false;
        }
        slow = slow.next;
        fast = fast.next.next;
    }
    return true;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 11:10:52