Skip to content

Commit edd1b6a

Browse files
committed
day3
1 parent 8058e02 commit edd1b6a

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed

RemoveNthNodeFromEndofList_19.java

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
package com.easy;
2+
3+
import java.util.HashMap;
4+
import java.util.LinkedList;
5+
6+
/**
7+
* Remove Nth Node From End of List
8+
* Given a linked list, remove the nth node from the end of list and return its head.
9+
*
10+
* author : quantin
11+
* date : 15/7/19
12+
*/
13+
public class RemoveNthNodeFromEndofList_19 {
14+
public class ListNode {
15+
int val;
16+
ListNode next;
17+
ListNode(int x) { val = x; }
18+
}
19+
20+
public ListNode removeNthFromEnd(ListNode head, int n) {
21+
if (head == null)
22+
return null;
23+
24+
if (head.next == null && n >= 1)
25+
return null;
26+
27+
LinkedList<ListNode> list = new LinkedList<>();
28+
ListNode p = head;
29+
30+
while (p != null) {
31+
list.add(p);
32+
p = p.next;
33+
}
34+
35+
int len = list.size();
36+
37+
if (n == 1) {
38+
list.get(len-2).next = null;
39+
} else if (n == len) {
40+
head = head.next;
41+
} else {
42+
list.get(list.size() - n - 1).next = list.get(list.size() - n + 1);
43+
}
44+
return head;
45+
}
46+
}

0 commit comments

Comments
 (0)