import java.util.List;
class ListNode{
int val;
ListNode next;
ListNode(int val,ListNode next){
this.val=val;
this.next=next;
}
}
public class SortList {
public static void display(ListNode head){
for(ListNode cur=head;cur!=null; cur=cur.next){
System.out.printf("(%d)->",cur.val);
}
System.out.println("null");
}
public static ListNode sortList(ListNode head){
if (head == null || head.next == null) {
return head;
}
ListNode fast = head.next;
ListNode slow = head;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
}
ListNode tmp = slow.next;
slow.next = null;
ListNode left = sortList(head);
ListNode right = sortList(tmp);
ListNode h = new ListNode(0,null);
ListNode res = h;
while (left != null && right != null) {
if (left.val < right.val) {
h.next = left;
left = left.next;
} else {
h.next = right;
right = right.next;
}
h = h.next;
}
h.next = left != null ? left : right;
return res.next;
}
public static void main(String[] args) {
ListNode n3=new ListNode(2,null);
ListNode n2=new ListNode(1,n3);
ListNode n1=new ListNode(3,n2);
display(n1);
n1=sortList(n1);
display(n1);
}
}
运行结果: