-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathleetCode_19.java
More file actions
42 lines (40 loc) · 1018 Bytes
/
Copy pathleetCode_19.java
File metadata and controls
42 lines (40 loc) · 1018 Bytes
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) {
head = reverse(head);
if(n == 1){
head = head.next;
if(head == null) return head;
return reverse(head);
}
int k = 1;
ListNode temp = head;
while(k < n){
if(k == n-1){
temp.next = temp.next.next;
break;
}
k++;
temp = temp.next;
}
return reverse(head);
}
ListNode reverse(ListNode head){
if(head.next == null){
return head;
}
ListNode hh = reverse(head.next);
head.next.next = head;
head.next = null;
return hh;
}
}