力扣网-删除链表的倒数第N个节点

问题简介

image-20220211152841493

编程思路

遍历思想

  • 由于程序的题意是删除倒数第N个节点,因此我们要定位到该节点进行删除。
  • 由于链表是单向的,因此,必须先获取链表的长度,然后通过倒数与整数的关系删除。
  • 要关注几个问题:这是边界情况
    • 删除第一个元素
    • 删除最后一个元素
    • 只有一个元素,删除此元素
    • 删除中间的元素,要保存当前节点的上一个节点的位置

 以五个元素为例,倒数第一个元素,为正数第5,倒数+整数=长度+1。

双指针思想

image-20220211163037419

代码编写

class ListNode {
    int val;
    ListNode next;

    ListNode() {
    }

    ListNode(int val) {
        this.val = val;
    }

    ListNode(int val, ListNode next) {
        this.val = val;
        this.next = next;
    }
}
    public ListNode removeNthFromEnd(ListNode head, int n) {
        int length = sizeOfListNode(head);
        if (length == 1 && n == 1) {
            return null;
        } else if (n == 1) {
            // 长度 > 1 并且删除最后一个
            return removeLast(head);
        } else if (n == length) {
            return head.next;
        }
        // 长度> 1 删除的也不是第一个
        int nth = length + 1 - n;
        int i = 1;
        ListNode node = head;
        ListNode pre = null;
        while (i<nth) {
            pre = node;
            node = node.next;
            i++;
        }
        pre.next = node.next;
        return head;
    }

    public ListNode removeLast(ListNode head) {
        ListNode node = head;
        while (node.next.next!=null) {
            node = node.next;
        }
        node.next = null;
        return head;
    }

    public int sizeOfListNode(ListNode head) {
        int length = 0;
        ListNode node = head;
        while (node != null) {
            length++;
            node = node.next;
        }
        return length;
    }

image-20220211160804258

总结

 这个问题也顺利的解决了,其实这个题目更加简单一些,因为只是涉及遍历,并且在遍历过程中去操作单链表。算是基础能力。

2022年2月11日16:15:28于宋营

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值