leetcode-19. Remove Nth Node From End of List

题目类型

链表

题意:

给出一个链表和一个数字n移除链表中从后往前的第n个节点,输出新的链表。

例子:

Given linked list: 1->2->3->4->5, and n = 2.

After removing the second node from the end, the linked list becomes 1->2->3->5.

我的思路:

65%

  • 先计算出链表的节点个数m,从后往前的第n个即为:从前往后的m - n + 1
  • 从前往后找到第m-n+1个节点为待删除节点, 将其前面节点的next指针更新为后一个节点,OK
class Solution {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode extra = new ListNode(0);//额外节点,防止head节点改变导致找不到原来的头
        extra.next = head;
        int count = 0;
        while (head != null) {
            count++;
            head = head.next;
        }
        int location = count - n + 1;
        head = extra.next;
        ListNode pre = null;
        for(int i = 1; i < location; i++){
            pre = head;
            head = head.next;
        }
        if (pre == null) {
            extra.next = extra.next.next;
        }
        else  pre.next = head.next;
        return extra.next;
    }
}

方法二:找待删除节点的新方法

beat 99%

待待删除节点到尾部的距离为n,可以设置一个slow,fast指针,初始为head,fast先从前往后移动n个位置,然后fast从当前位置移动到末尾的同时移动slow,那么fast到末尾时slow恰好到该删除的节点的上一个。
- 注意:边界情况的判断
- 若head为null,return null
- 若删除为第一个节点
- 若n大于链表长度

class Solution {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        if(head == null) return null;
        ListNode copy = head;
        ListNode copy2 = head;
        while(n-- > 0){
            if(head.next == null){
                if(n == 0) return copy.next;//删除的为第一个节点
                else return null;//n大于链表长度
            }
            head = head.next;
        }
        while(head.next != null){
            head = head.next;
            copy2 = copy2.next;
        }
        copy2.next = copy2.next.next;
        return copy;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值