leetcode----删除链表中的倒数第N个节点

本文介绍了一种高效算法,用于删除单链表中倒数第N个节点,提供两种方法:一是利用哈希映射进行编号存储;二是采用双指针技巧。这两种方法均可在一次遍历内完成任务。

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

题目:给你一个链表,删除链表的倒数第 n 个结点,并且返回链表的头结点。

示例 1:

输入:head = [1,2,3,4,5], n = 2
输出:[1,2,3,5]

示例 2:

输入:head = [1], n = 1
输出:[]

示例 3:

输入:head = [1,2], n = 1
输出:[1]

算法:(1)进行一次遍历,在遍历途中使用一个map来进行编号存储,编号从1开始,删除的节点就为链表长度-n+1。

算法:(2)使用双指针,fast指针比slow指针快n个长度,那么当fast指针指向链表末尾的时候,slow指针刚好指向倒数第n个节点。

代码实现:

(1)

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        if(head.next == null){
            return null;
        }
        ListNode temp = head;
        ListNode res = temp;
        int index = 1;
        Map<Integer, ListNode> map = new HashMap<Integer, ListNode>();
        while(head.next != null){
            map.put(index, head);
            head = head.next;
            index++;
        }
        if(n == index){
            return res.next;
        }
        ListNode node = map.get(index - n);
        if(node.next.next != null){
            node.next = node.next.next;
        }else{
            node.next = null;
        }
        while(temp != node){
            temp = temp.next;
        }
        temp.next = node.next;
        return res;
    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值