链表快排

来源:互联网 发布:增值税发票模拟软件 编辑:程序博客网 时间:2024/06/08 19:56
class Solution{public:ListNode* sortList(ListNode* head){if(head == NULL || head->next == NULL)return head;ListNode* begin = head, *end = NULL;Quicksort_list(begin, end);return begin;}void Quicksort_list(ListNode* begin, ListNode* end){ListNode* curnode = NULL;if(begin != end){curnode = partition(begin, end);Quicksort_list(begin, curnode);Quicksort_list(curnode->next, end);}}ListNode* partition(ListNode* begin, ListNode* end){int key = begin->val;ListNode* p = begin, * q = p->next;while(q){if(q->val < key)  //精髓{p = p->next;swap(p->val, q->val);}q = q->next;}swap(begin->val, p->val);return p;}void scanList(ListNode* head){while(head != NULL){cout<<head->val;if(head->next != NULL)cout<<"->";head = head->next;}}};

0 0
原创粉丝点击