-
Notifications
You must be signed in to change notification settings - Fork 56
/
Solution.java
40 lines (34 loc) · 1.04 KB
/
Solution.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
package g0001_0100.s0019_remove_nth_node_from_end_of_list;
// #Medium #Top_100_Liked_Questions #Top_Interview_Questions #Two_Pointers #Linked_List
// #Algorithm_I_Day_5_Two_Pointers #Level_2_Day_3_Linked_List #Big_O_Time_O(L)_Space_O(L)
// #2024_02_11_Time_0_ms_(100.00%)_Space_41.7_MB_(44.22%)
import com_github_leetcode.ListNode;
/*
* 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; }
* }
*/
public class Solution {
private int n;
public ListNode removeNthFromEnd(ListNode head, int n) {
this.n = n;
ListNode node = new ListNode(0, head);
removeNth(node);
return node.next;
}
private void removeNth(ListNode node) {
if (node.next == null) {
return;
}
removeNth(node.next);
this.n--;
if (this.n == 0) {
node.next = node.next.next;
}
}
}