-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSortList.java
More file actions
31 lines (27 loc) · 730 Bytes
/
Copy pathSortList.java
File metadata and controls
31 lines (27 loc) · 730 Bytes
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
package linkedlist;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
// 148. Sort List https://leetcode.com/problems/sort-list/
//Todo Use MergeSort for O(1) space and ologn
public class SortList {
public ListNode sortList(ListNode head) {
if(head==null)return head;
List<Integer> vals= new ArrayList<>();
ListNode node=head;
while(node!=null){
vals.add(node.val);
node= node.next;
}
Collections.sort(vals);
ListNode n=new ListNode();
ListNode ret= n;
for(int i=0;i<vals.size();i++){
n.val=vals.get(i);
if(i<vals.size()-1)
n.next=new ListNode();
n=n.next;
}
return ret;
}
}