LeetCode Remove Nth Node From End of List

本文介绍了一种高效解决链表问题的方法——双指针法,并详细解释了其原理及应用,包括如何在一次遍历中找到并删除链表的倒数第N个节点。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

原题链接在这里:https://leetcode.com/problems/remove-nth-node-from-end-of-list/

Method 1: 算出总长度,再减去n,即为要从头多动的点。但要新要求,only one pass。

Method 2: 两个指针,一个runner,一个walker,runner先走n步,随后runner和walker一起走,直到runner指为空。

Note: 1. 都是找到要去掉点的前一个点记为mark,再通过mark.next = mark.next.next去掉对应应去掉的点。

2. 注意去掉list头点的情况,e.g. 1->2, n = 2.


AC Java:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        /*Method 1
        if(head == null)
            return head;
        int len = 0;
        ListNode temp = head;
        while(temp != null){
            temp = temp.next;
            len++;
        }
        if(len < n){
            return head;
        }
        int moveNum = len - n;
        ListNode dunmy = new ListNode(0);
        dunmy.next = head;
        temp = dunmy;
        while(moveNum > 0){
            temp = temp.next;
            moveNum--;
        }
        temp.next = temp.next.next;
        return dunmy.next;
        */
        
        //Method 2
        if(head == null || n == 0)
            return head;
        ListNode dunmy = new ListNode(0);
        dunmy.next = head;
        ListNode runner = dunmy.next;
        ListNode walker = dunmy;
        while(n>0 && runner != null){
            runner = runner.next;
            n--;
        }
        while(runner != null){
            runner = runner.next;
            walker = walker.next;
        }
        walker.next = walker.next.next;
        return dunmy.next;
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值