題目描述:給鏈表排序
input : 4->2->1->3 output : 1->2->3->4
思路:要求在O(nlgn)時間複雜度內,合適的排序方法快排,堆排,歸併,還有O(n)的基數排序桶排序
鏈表的特點不能通過下標訪問,堆排一般是數組形式,所以最好採用歸併排序(遞歸操作)
溫故而知新:回顧下歸併排序,將兩個已經排好序的序列合併成一個有序序列merge,有遞歸和非遞歸兩種,兩路歸併就是兩兩合併
那麼對於無序鏈表來說,怎麼纔是有序鏈表,當然是只有一個節點的是有序鏈表
所以就把問題不斷分解,直到鏈表內只有一個節點
一個鏈表不斷分成兩半,直到分到只有一個節點,然後往上回溯,合併,調用合併有序鏈表
鏈表分成兩個中點使用快慢指針法,快指針走兩步,慢指針走一步,當快指針走到末尾,慢指針就來到鏈表中點
#include<iostream>
using namespace std;
struct ListNode{
int data;
ListNode* next;
ListNode(int x) : data(x), next(NULL){}
};
void show(ListNode* head)
{
if(head == NULL)
{
cout << "NULL";
}
ListNode* p = head;
while(p)
{
cout << p->data;
p = p->next;
}
cout << endl;
}
ListNode* createList(int n)//尾插法創建鏈表
{
ListNode* head = new ListNode(0);
ListNode* newNode;
ListNode* rear = head;
for(int i = 0; i < n; i++)
{
int data;
cin >> data;
newNode = new ListNode(data);
rear->next= newNode;
rear = newNode;
}
rear->next = NULL;
return head->next;
}
class Solution{
public:
ListNode* sortList(ListNode* head)
{
if(!head || !head->next) return head;
ListNode* fast = head, *slow = head, *pre = head;
while(fast && fast->next)//快指針走兩步慢指針走一步,快指針走到鏈表末尾,慢指針剛好走到中間位置
{
pre = slow;
slow = slow->next;
fast = fast->next->next;
}
pre->next = NULL;
return mergeList(sortList(head), sortList(slow));
}
ListNode* mergeList(ListNode* l1, ListNode* l2)//合併鏈表
{
if(l1 == NULL) return l2;
if(l2 == NULL) return l1;
ListNode* dummy = new ListNode(0);
ListNode* head = dummy;
while(l1 && l2)
{
if(l1->data < l2->data)
{
head ->next = l1;
l1 = l1->next;
}
else{
head->next = l2;
l2 = l2->next;
}
head = head->next;
}
head ->next = l1 ? l1 : l2;
return dummy->next;
}
};
int main()
{
ListNode* l = createList(4);
show(l);
Solution s;
ListNode *l1 = s.sortList(l);
show(l1);
return 0;
}