题目描述1 单链表排序问题
Sort a linked list in O(n log n) time using constant space complexity.
用归并排序: 其中只是创建了一个preHead节点 占用空间O(1) 时间O(nlogn)
public class Solution { public ListNode sortList(ListNode head) { if(head == null || head.next == null) { return head; } //常规合并排序思路 ListNode mid = getMid(head); ListNode midNext = mid.next; mid.next = null; //一定记得断开head 左半部分的链表尾部 return mergeSort(sortList(head), sortList(midNext)); } private ListNode getMid(ListNode head) { //使用快慢指针获取中间节点位置 if(head == null || head.next == null) { return head; } ListNode slow = head, quick = head; while(quick.next != null && quick.next.next != null) { slow = slow.next; quick = quick.next.next; } return slow; } private ListNode mergeSort(ListNode n1, ListNode n2) { 对两个分链表进行合并 ListNode preHead = new ListNode(0), cur1 = n1, cur2 = n2, cur = preHead; while(cur1 != null && cur2 != null) { if(cur1.val < cur2.val) { cur.next = cur1; cur1 = cur1.next; } else { cur.next = cur2; cur2 = cur2.next; } cur = cur.next; } cur.next = cur1 == null ? cur2 : cur1; //看哪个链表不为空 继续接上 return preHead.next; } }
用快速排序:
public class Solution { public ListNode sortList(ListNode head) { quickSort(head, null); //头尾节点 return head; } public static void quickSort(ListNode head, ListNode end) { if(head != end) { ListNode
partition= partition(head);quickSort(head, partition); //分解成两部分 quickSort(partition.next, end); } } public static ListNode partition(ListNode head) { ListNode slow = head; ListNode fast = head.next; while (fast != null) { if(fast.val < head.val) { slow = slow.next; fast.val = slow.val ^ fast.val ^ (slow.val = fast.val); } fast = fast.next; } slow.val = head.val ^ slow.val ^ (head.val = slow.val); return slow; }}