Remove Nth Node From End of List

本文介绍了一种高效算法,用于在一过式遍历中移除链表倒数第N个节点。通过设置两个指针,使其中一个先于另一个前进N步,当先进行的指针到达链表尾部时,后方的指针恰好位于待删除节点的前一个位置,从而实现快速删除。
/*
正常方法需要遍历一遍获取长度,然后找到n跳过
one pass方法思路:
       n = 2
           |
       1 2 3 4
first0 1 2 3
       | | |
           | |
sec  0 1 2
       | |-> 4
1 建立两个listnode 用于操作 
2 让第一个listnode先走到 n所在的位置
3 然后 两个listnode同时走到第一个结束 这时第二个listnode正好在n位置的前一个
4 然后跳过即可。
注意: 为了避免越界 先建立一个以0 开头的listnode 把next付给head return时直接return next就好;
*/


/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode result = new ListNode(0);
        result.next = head;
        ListNode first = result;
        ListNode second = result;
        for(int i = 0; i <= n; i++) {
            first = first.next;
        }
        while(first != null) {
            first = first.next;
            second = second.next;
        }
        second.next = second.next.next;
        return result.next;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值