1
class Solution {
2
public ListNode removeNthFromEnd(ListNode head, int n) {
3
ListNode temp = head;
4
int len = 0;
5

6
if (head == null || head.next == null) return null;
7

8
while (temp != null) {
9
temp = temp.next;
10
len++;
11
}
12

13
if (len == n) return head.next;
14

15
int frontlen = len - n - 1;
16

17
ListNode first = head.next;
18
ListNode second = head;
19

20
int count = 0;
21

22
while (first != null) {
23
if (count == frontlen) {
24
second.next = first.next;
25
break;
26
} else {
27
first = first.next;
28
second = second.next;
29
count++;
30
}
31
}
32

33
return head;
34
}
35
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0