-
Notifications
You must be signed in to change notification settings - Fork 31
/
19.java
42 lines (38 loc) · 995 Bytes
/
19.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
if(head.next == null){
return null;
}
ListNode current = head;
int i = 0;
while(current != null){
i++;
current = current.next;
}
if(i-n == 0){
head = head.next;
return head;
}
int j = 0;
current = head;
while(current != null){
if(j == i-n-1){
current.next = current.next.next;
}else{
current = current.next;
}
j++;
}
return head;
}
}