-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathDay70.java
More file actions
52 lines (42 loc) · 1.23 KB
/
Day70.java
File metadata and controls
52 lines (42 loc) · 1.23 KB
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
43
44
45
46
47
48
49
50
51
class ListNode {
int val;
ListNode next;
ListNode(int val) {
this.val = val;
this.next = null;
}
}
public class Day70 {
public ListNode removeNthFromEnd(ListNode head, int k) {
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode slow = dummy;
ListNode fast = dummy;
for (int i = 0; i <= k; i++) {
if (fast == null)
return head;
fast = fast.next;
}
while (fast != null) {
slow = slow.next;
fast = fast.next;
}
slow.next = slow.next.next;
return dummy.next;
}
public static void main(String[] args) {
RemoveKthNode solution = new RemoveKthNode();
// Example usage
ListNode head = new ListNode(1);
head.next = new ListNode(2);
head.next.next = new ListNode(3);
head.next.next.next = new ListNode(4);
int k = 2;
ListNode result = solution.removeNthFromEnd(head, k);
while (result != null) {
System.out.print(result.val + " -> ");
result = result.next;
}
System.out.println("NULL");
}
}