- 使用值排序可以借助快排来实现单链表的排序
- 借一张图:
- 代码如下:
struct ListNode{
ListNode * next;
int val;
ListNode(ListNode * _next, int _val) :
next(_next), val(_val){}
};
ListNode * getPartion(ListNode * pHead, ListNode * pEnd)
{
int key = pHead->val;
ListNode * p = pHead;
ListNode * q = pHead->next;
while (q != pEnd->next){
if (q->val < key){
p = p->next;
swap(p->val, q->val);
}
q = q->next;
}
swap(pHead->val, p->val);
return p;
}
ListNode * quickSort(ListNode * pBegin, ListNode * pEnd)
{
if (pBegin != pEnd){
ListNode * mid = getPartion(pBegin, pEnd);
quickSort(pBegin, mid);
quickSort(mid->next, pEnd);
}
return pBegin;
}
public static void main(String[] args) {
print p = new print();
ListNode node1 = new ListNode(3);
ListNode node2 = new ListNode(2);
ListNode node3 = new ListNode(4);
ListNode node4 = new ListNode(1);
ListNode node5 = new ListNode(5);
ListNode node6 = new ListNode(6);
node1.next = node2;
node2.next = node3;
node3.next = node4;
node4.next = node5;
node5.next = node6;
ListNode res = p.quickSortLinkedList(node1, node6);
System.out.println(res.val + " " + res.next.val + " " + res.next.next.val);
}
ListNode getPartion(ListNode begin, ListNode end) {
if (begin == end || end == null)
return null;
ListNode p = begin, q = begin.next;
while (q != end.next) {
if (q.val < begin.val) {
p = p.next;
swap(p, q);
}
q = q.next;
}
swap(begin, p);
return p;
}
private void swap(ListNode node1, ListNode node2) {
int tmp = node1.val;
node1.val = node2.val;
node2.val = tmp;
}
ListNode quickSortLinkedList(ListNode begin, ListNode end) {
ListNode mid = getPartion(begin, end);
if (mid != null) {
quickSortLinkedList(begin, mid);
quickSortLinkedList(mid.next, end);
}
return begin;
}