-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathListNthNodeRemove.java
More file actions
46 lines (38 loc) · 1.17 KB
/
ListNthNodeRemove.java
File metadata and controls
46 lines (38 loc) · 1.17 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
//https://leetcode.com/problems/remove-nth-node-from-end-of-list/submissions/1486761033/
class ListNthNodeRemove {
public ListNode removeNthFromEnd(ListNode head, int n) {
int count = 0;
ListNode current = head;
while (current != null) {
count++;
current = current.next;
}
int index = count - n;
if (index == 0)
head = head.next;
else {
current = head;
for (int i = 0; i < index - 1; i++)
current = current.next;
current.next = current.next.next;
}
return head;
}
public static void main(String[] args) {
ListNode head = new ListNode();
ListNode current = head;
for (int i = 1; i < 10; i++) {
current.val = i;
current.next = new ListNode();
current = current.next;
}
current.val = 10;
ListNthNodeRemove lr = new ListNthNodeRemove();
head = lr.removeNthFromEnd(head, 10);
current = head;
while (current != null) {
System.out.print(current.val + " ");
current = current.next;
}
}
}