-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLeetCode0019.java
More file actions
58 lines (52 loc) · 1.71 KB
/
Copy pathLeetCode0019.java
File metadata and controls
58 lines (52 loc) · 1.71 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
52
53
54
55
56
57
58
/* Remove Nth Node From End of List
* Example:
* Given linked list: 1->2->3->4->5, and n = 2.
* After removing the second node from the end, the linked list becomes 1->2->3->5.
* */
public class LeetCode0019 {
public static void main(String args[]){
int[] input = new int[]{1,2};
ListNode head = buildListNode(input);
int n = 2;
ListNode output = removeNthFromEnd(head, n);
while (output != null) {
System.out.println(output.val);
output = output.next;
}
}
public static ListNode removeNthFromEnd(ListNode head, int n) {
ListNode dummyHead = new ListNode(0);
dummyHead.next = head;
ListNode pointer1 = dummyHead;
ListNode pointer2 = dummyHead;
for(int i = 0; i <= n; i++)
pointer1 = pointer1.next;
if(pointer1 == null){
head = head.next;
return head;
}
while(pointer1 != null){
pointer1 = pointer1.next;
pointer2 = pointer2.next;
}
pointer2.next = pointer2.next.next;
return head;
}
private static ListNode buildListNode(int[] input) {
ListNode first = null, last = null, newNode;
if (input.length > 0) {
for (int i = 0; i < input.length; i++) {
newNode = new ListNode(input[i]);
newNode.next = null;
if (first == null) {
first = newNode;
last = newNode;
} else {
last.next = newNode;
last = newNode;
}
}
}
return first;
}
}