您的位置:首页 > 其它

LeetCode OJ:Sort List(排序链表)

2015-10-23 10:01 316 查看
Sort a linked list in O(n log n) time using constant space complexity.

题目要求在常数控件内以O(nlogn)的事件复杂度来排序链表。

常数空间内我没有实现,O(nlogn)的话使用归并排序就可以了吗, 下面是代码:

/**
* 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) {
if(!head || !head->next)
return head;
return mergeSort(head);
}

ListNode * mergeSort(ListNode * head)
{
if(head == NULL || head->next == NULL) return head;
ListNode * fastP = head;
ListNode * slowP = head;
ListNode * slowPre = slowP; //这里生成快慢指针的时候应该注意一点,选一个pre节点,否则直接用slowP的话那么分成的两段是不平衡的
for(; fastP != NULL && fastP->next != NULL; fastP = fastP->next->next, slowP = slowP->next){
slowPre = slowP;
}
ListNode * head1 = head;
ListNode * head2 = slowP;
slowPre->next = NULL;//截断list
head1 = mergeSort(head1);
head2 = mergeSort(head2);
return merge(head1, head2);
}

ListNode * merge(ListNode * head1, ListNode * head2)
{
ListNode * ret = new ListNode(0);   //记录首节点的位置
ListNode * helper = ret;    //这里应该注意,helper是用来标记下一个插入位置用的。
while(head1 && head2){
if(head1->val < head2->val){
helper->next = head1;
head1 = head1->next;
}else{
helper->next = head2;
head2 = head2->next;
}
helper = helper->next;//指向当前链表的尾节点
}
if(head1 == NULL)
helper->next = head2;
else
helper->next = head1;
helper = ret->next;
ret->next = NULL;  //销毁helper节点
delete ret;
return helper;
}

};


下面的事java版,写了很多的局部变量,主要事图个方便啊,方法与上相同,可以满足题目的限制条件。代码如下所示:

public class Solution {
public ListNode sortList(ListNode head) {
if(head == null || head.next == null)
return head;
return mergeSort(head);
}

public ListNode mergeSort(ListNode head){
if(head == null || head.next == null) return head;
ListNode fast = head;
ListNode slow = head;
ListNode slowPre = new ListNode(-1);
slowPre.next = head;
while(fast != null){
fast = fast.next;
slow = slow.next;
slowPre = slowPre.next;
if(fast != null)
fast = fast.next;
}
ListNode list1 = head;
ListNode list2 = slow;
slowPre.next = null;
list1 = mergeSort(list1);
list2 = mergeSort(list2);
return merge(list1, list2);
}

public ListNode merge(ListNode head1, ListNode head2){
if(head1 == null) return head2;
if(head2 == null) return head1;
ListNode helperP = new ListNode(-1);
helperP.next = head1;
ListNode pPre = helperP;
ListNode p = head1;
ListNode helperQ = new ListNode(-1);
helperQ.next = head2;
ListNode qPre = helperQ;
ListNode q = head2;
while(p != null && q != null){
if(p.val < q.val){
p=p.next;
pPre = pPre.next;
}else{
pPre.next = q;
qPre.next = q.next;
q.next = p;
q = qPre.next;
pPre = pPre.next;
}
}
if(p == null){
pPre.next = helperQ.next;
helperQ.next = null;
}
return helperP.next;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: