Skip to content

Commit 0492e50

Browse files
committed
solution for: Sort List with merge sort
1 parent c2b768b commit 0492e50

File tree

1 file changed

+60
-0
lines changed

1 file changed

+60
-0
lines changed

src/leetcode/SortListTest.java

+60
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
package leetcode;
2+
3+
public class SortListTest {
4+
5+
public static void main(String[] args) {
6+
SortListTest test = new SortListTest();
7+
ListNode l = new ListNode(4);
8+
l.next = new ListNode(3);
9+
l.next.next = new ListNode(1);
10+
ListNode re= test.sortList(l);
11+
System.out.println(re.val);
12+
}
13+
14+
public ListNode sortList(ListNode head) {
15+
if(head ==null || head.next==null) return head;
16+
ListNode fast = head;
17+
ListNode slow = head;
18+
ListNode prev= null;
19+
while(fast!=null && fast.next!=null){
20+
prev=slow;
21+
fast= fast.next.next;
22+
slow= slow.next;
23+
}
24+
prev.next=null;
25+
ListNode l1 = sortList(head);
26+
ListNode l2 = sortList(slow);
27+
return merge(l1,l2);
28+
}
29+
30+
public ListNode merge(ListNode l1, ListNode l2){
31+
ListNode result = new ListNode(0);
32+
ListNode l= result;
33+
while(l1!=null && l2!=null){
34+
if(l1.val < l2.val){
35+
l.next = l1;
36+
l1= l1.next;
37+
}
38+
else{
39+
l.next = l2;
40+
l2= l2.next;
41+
}
42+
l= l.next;
43+
}
44+
45+
if(l1!=null)
46+
l.next= l1;
47+
if(l2!=null)
48+
l.next = l2;
49+
return result.next;
50+
}
51+
52+
}
53+
54+
class ListNode{
55+
int val;
56+
ListNode next;
57+
ListNode(int x){
58+
val=x;
59+
}
60+
}

0 commit comments

Comments
 (0)