LeetCode 19. Remove Nth Node From End of List

tag:List

Difficulty:Medium

Problem 

Given the head of a linked list, remove the nth node from the end of the list and return its head.

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

Input: head = [1,2,3,4,5], n = 2
Output: [1,2,3,5]
Input: head = [1], n = 1
Output: []

Solutions

解法一:

首先看一种简单的解法。2次遍历链表,统计个数+删除

先统计个数,然后做减法得到要删除的是正数第几个,删除。

注意:count==0代表要删除的是第一个元素,直接返回

public ListNode removeNthFromEnd1(ListNode head, int n) {
    ListNode p = head;
    int sum = 0;
    while (p != null) {
        p = p.next;
        sum++;
    }
    int count = sum - n;
    if (count == 0) {
        return head.next;
    }
    ListNode pre = head;
    p = head.next;
    while (count > 1 && p.next != null) {
        pre = p;
        p = p.next;
        count--;
    }
    pre.next = p.next;
    return head;
}

解法二:

能不能遍历一次呢?

遍历一次意味着不要统计了,找到直接删除

因此,需要两个指针遍历链表(比较像快慢指针

首先,p指针向前走n步,如果指向空,说明要删除的是首元素,那么返回head.next即可。

然后,p指针和pre指针同时往前走,直到p为最后一个元素停止,此时pre指向要移除元素的前一个

最后,修改pre指针跳过要移除元素

public ListNode removeNthFromEnd(ListNode head, int n) {
    ListNode p = head, pre = head;
    while (n != 0) {
        p = p.next;
        n--;
    }
    if (p == null) {
        return head.next;
    }
    while (p.next != null) {
        p = p.next;
        pre = pre.next;
    }
    pre.next = pre.next.next;
    return head;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值