Sort a linked list in O(n log n) time using constant space complexity.
学习了网上的帖子,用归并排序,注意空间复杂度超了,记得重做
Source
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode sortList(ListNode head) { //nlogn 只能在快排、归并、堆中选择排序方法
//递归体 不要在这里将p,q赋值为head
if(head == null || head.next == null) //head.next==null是递归到只剩一个元素的判断条件
return head;
ListNode p = findMid(head);
ListNode q = p.next;
p.next = null; //***
p = head;
p = sortList(p);
q = sortList(q);
ListNode a = merge(p,q);
return a;
}
public ListNode findMid(ListNode head){
ListNode p = head, q = head;
while(p.next != null && p.next.next != null){ //判断p.next.next前一定要先判断p.next 否则如果p.next为null就找不到p.next.next了 另外找链表中位的时候判断条件一定是 next和next.next 而不能是本身和next
p = p.next.next;
q = q.next;
}
return q;
}
public ListNode merge(ListNode p, ListNode q){ //***
ListNode st = new ListNode(0);
st.next = p;
ListNode k = st;
while(p != null && q != null){ //p,q单步走只需判断本身是否等于null
if(p.val <= q.val){
p = p.next;
}
else{
ListNode temp = q.next;
q.next = k.next;
k.next = q;
q = temp;
}
k = k.next;
}
if(q != null){
k.next = q;
}
return st.next;
}
}
Test
public static void main(String[] args){
ListNode a = new ListNode(5);
a.next = new ListNode(2);
a.next.next = new ListNode(7);
a.next.next.next = new ListNode(9);
a.next.next.next.next = new ListNode(1);
a.next.next.next.next.next = new ListNode(6);
ListNode b = new Solution().sortList(a);
while(b != null){
System.out.println(b.val);
b = b.next;
}
}