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
- We should first know the length L of the list node.
- 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;
}
}
博客围绕链表移除倒数第n个节点展开,介绍了两种解法。一是暴力法,先确定链表长度L,再从头找到第L - n个节点并修改其指向,时间复杂度O(2L),空间复杂度O(1);二是单遍法,用两个指针,第二指针领先第一指针n + 1,时间复杂度O(L),空间复杂度O(1)。
8384

被折叠的 条评论
为什么被折叠?



