算法十九:删除链表的倒数第 N 个结点

删除链表的倒数第 N 个结点

算法内容

给你一个链表,删除链表的倒数第 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]

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/remove-nth-node-from-end-of-list

算法思想

该算法在学《数据结构与算法》这一门课程时,都会接触到这一算法,这里我们依然用图来简单的介绍一下该算法思想:

  • 普通链表(链表长度>n)

图1

  • 特殊状态(算法长度=n)

图2

整体算法

public class Day_17 {
    static Scanner input=new Scanner(System.in);
    public static ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode after=head;
        ListNode first=head;
        ListNode changes=head;
        for (int i = 0; i < n-1; i++) {
            after=after.next;
        }
        if (after.next==null){
            return first.next;
        }
        while (after.next!=null){
            changes=first;
            after=after.next;
            first=first.next;
        }
        changes.next=first.next;
        return head;
    }
    public static ListNode input_link_test(int n, ListNode head){
        ListNode temp=head;
        for (int i = 0; i < n-1; i++) {
            int num =input.nextInt();
            ListNode listNode=new ListNode(num,null);
            temp.next=listNode;
            temp=temp.next;
        }
        return head;
    }
    public static void main(String[] args) {
        System.out.print("输入单链表长度n:");
        int n=input.nextInt();
        System.out.println("----------------------------------------------------------");
        System.out.print("输入删除倒数第几个数字:");
        int num_count=input.nextInt();
        System.out.println("-----------------------------------------------------------");
        System.out.println("输入测试数字:");
        int num =input.nextInt();
        ListNode head=new ListNode(num,null);
        input_link_test(n,head);
        System.out.println("-----------------------------------------------------------");
        head=removeNthFromEnd(head,num_count);
        while (head!=null){
            System.out.println(head.val);
            head=head.next;
        }
    }
}

尾语

以上属于个人见解,有好的想法可以在下方评论写出自己的想法,大家一起进步。该题是力扣上的题,若有侵权,请及时告知。该题链接:https://leetcode-cn.com/problems/remove-nth-node-from-end-of-list

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Lveson

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值