Leetcode 19. Remove Nth Node From End of List [medium][java]

博客围绕链表移除倒数第n个节点展开,介绍了两种解法。一是暴力法,先确定链表长度L,再从头找到第L - n个节点并修改其指向,时间复杂度O(2L),空间复杂度O(1);二是单遍法,用两个指针,第二指针领先第一指针n + 1,时间复杂度O(L),空间复杂度O(1)。

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

Note
Given n will always be valid.

Example
在这里插入图片描述

Ignored Case
Boundary Problem
在这里插入图片描述

Consideration

  1. We should first know the length L of the list node.
  2. Then, we restart searching from the beginning until we find the L-n th node.Change this node’s next.

Solution 1: Brute force
Time complexity: O(L), where L is the length of the node list. In the first loop, we iterate L times. In the second loop. we iterate L-n times. Therefore, the total loop is L+L-n, which is O(2L).
Space Complexity: O(1).

class Solution {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        ListNode dup = head;
        int length = 0;
        while(dup != null) {
            ++length;
            dup = dup.next;
        }
        length -= n;
        dup = dummy;
        while(length > 0) {
            dup = dup.next;
            length--;
        }
        dup.next = dup.next.next;
        return dummy.next;
    }
}

Solution 2: one pass
Use two pointers to iterate the list node. The second pointer is n+1 ahead of the first pointer. When the second pointer points to null, the first pointer points to the node right before the last n-th node.
Time complexity: O(L), where L is the length of the node list. In the first loop, we iterate n +1 times. In the second loop. we iterate L-n-1 times. Therefore, the total loop is O(L).
Space Complexity: O(1).

class Solution {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        ListNode first = dummy;
        ListNode second = dummy;
        for (int i = 1; i <= n + 1; i++) {
            second = second.next;
        }
        
        while(second != null) {
            second = second.next;
            first = first.next;
        }

        first.next = first.next.next;
        
        return dummy.next;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值