Given a linked list, remove the nth node from the end of list and return its head. For 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.
Solution
Honestly I don’t know how my first solution got accepted, basically I just count the size of list and then remove that element in the second pass.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode cur=head;
int i=0;
while(cur!=null){cur=cur.next;i++;}
System.out.println(i);
ListNode cur2=head;
if(n==i){head=head.next;}
for(int j=0;j<i-n-1;j++){
System.out.println(j);
cur2=cur2.next;
}
if (cur2.next == null) {
returnnull;
}
else cur2.next=cur2.next.next;
return head;
}
One pass solution using two pointers: one fake pointer to move n steps from the beginning, then move both pointers until list ends.
1
2
3
4
5
6
7
8
9
10
11
12
13
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode cur=head;
ListNode p=head;
for(int i=0;i<n;i++){cur=cur.next;}
//deal with removing head cases
if(cur==null) head=head.next;
//made a mistake here, forgot to move cur with p...
Or, instead of dividing into two parts, we can use ArrayDeque Class. (Similar to brute force solution, merges two list each time, whose complexity is n(2+3+…k)=O(nk^2))
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public ListNode mergeKLists(List<ListNode> lists) {
if(lists == null || lists.isEmpty()) returnnull;
ArrayDeque<ListNode> q = new ArrayDeque<ListNode>();
for(ListNode n : lists) {
if (n != null) q.offer(n);
}
while(q.size() > 1) {
ListNode a = q.poll();
ListNode b = q.poll();
q.offer(mergeTwoLists(a, b));
}
return q.poll();
}
Second Solution is PQ. We can add the heads of all lists into the queue. And we can poll out the smallest one. If the next node of this smallest node is not null, we can add the next node to the queue. Until we empty the PQ, we get the sorted lists. The complexity is also O(nklogk).
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
public ListNode mergeKLists(List<ListNode> lists) {
if(lists == null || lists.isEmpty()) returnnull;
PriorityQueue<ListNode> heap=new PriorityQueue<>(lists.size(), new Comparator<ListNode>(){