Sort List
Total Accepted: 453 Total Submissions: 2621Sort a linked list in O(n log n) time using constant space complexity.
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *sortList(ListNode *head) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
//merge sort
return mergeSort(head);
}
ListNode* mergeSort(ListNode* head) {
if(head==NULL || head->next==NULL) return head;
//split
ListNode* p=head; ListNode* q=head;
ListNode* pre = p;
while(q!=NULL && q->next!=NULL) {
q=q->next->next;
pre = p;
p=p->next;
}
pre->next = NULL;
ListNode* h1 = mergeSort(head);
ListNode* h2 = mergeSort(p);
return merge(h1,h2);
}
ListNode* merge(ListNode* h1, ListNode* h2) {
ListNode* dump = new ListNode(0);
ListNode* p = dump;
while(h1!=NULL && h2!=NULL) {
if(h1->val<h2->val){
p->next = h1;
h1 = h1->next;
} else {
p->next = h2;
h2 = h2->next;
}
p = p->next;
}
if(h1!=NULL) p->next = h1;
else p->next = h2;
ListNode* head = dump->next;
delete dump;
return head;
}
};
/* 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) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
if(head==null || head.next==null) return head;
ListNode p,q;
p = q =head;
ListNode pre=p;
while(q!=null && q.next!=null) {
q= q.next.next;
pre=p;
p = p.next;
}
pre.next = null;
return merge( sortList(head), sortList(p));
}
private ListNode merge(ListNode h1, ListNode h2) {
ListNode head = new ListNode(0);
ListNode p = head;
while(h1!=null && h2!=null) {
if(h1.val<h2.val){
p.next = h1;
h1 = h1.next;
} else {
p.next = h2;
h2 = h2.next;
}
p = p.next;
}
p.next = h1!=null? h1 : h2;
return head.next;
}
}