-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRemoveNthNodeFromEndOfList.java
62 lines (49 loc) · 1.48 KB
/
RemoveNthNodeFromEndOfList.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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
package com.leetcode.algorithms.medium.linkedlist;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import com.leetcode.util.InputUtil;
import com.leetcode.util.ListNode;
public class RemoveNthNodeFromEndOfList {
public static void main(String...strings) {
// Input
Scanner scanner = new Scanner(System.in);
String[] inputs = InputUtil.inputArr(scanner.next());
int n = scanner.nextInt();
ListNode listNode = null;
for (String input : inputs) {
listNode = insertListNode(listNode, Integer.parseInt(input));
}
// Remove kth from end
listNode = removeNthFromEnd(listNode, n);
while (listNode != null) {
System.out.print(listNode.val + " >> ");
listNode = listNode.next;
}
System.out.print("null");
scanner.close();
}
static ListNode insertListNode(ListNode listNode, int val) {
if (listNode == null) {
listNode = new ListNode(val);
} else {
listNode.next = insertListNode(listNode.next, val);
}
return listNode;
}
static ListNode removeNthFromEnd(ListNode head, int n) {
// Save List Node as Collection
List<Integer> list = new ArrayList<Integer>();
while(head != null) {
list.add(head.val);
head = head.next;
}
// Remove kth from end
list.remove(list.size() - n);
// Save updated Collection as List Node
for (int i = 0; i < list.size(); i++) {
head = insertListNode(head, list.get(i));
}
return head;
}
}