赞
踩
原题链接
时间复杂度:
O
(
n
l
o
g
n
)
O(nlogn)
O(nlogn) 用主定理可以求得
空间复杂度:
O
(
l
o
g
n
)
O(logn)
O(logn) 最多需要这么多栈空间
说明:
注意:如果选择左端点,最坏情况会退化到 O ( n 2 ) O(n^2) O(n2)
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode *getTail(ListNode *head) { while (head->next) head = head->next; return head; } ListNode *quickSortList(ListNode *head) { // 遍历链表,按照三种情况分别加到三个链表中 // 空结点或单结点 if (!head || !head->next) return head; ListNode *lhead = new ListNode(-1), *mhead = new ListNode(-1), *rhead = new ListNode(-1); auto left = lhead, mid = mhead, right = rhead; // 遍历链表 int x = head->val; for (auto p = head; p; p = p->next) { if (p->val < x) left = left->next = p; else if (p->val == x) mid = mid->next = p; else right = right->next = p; } // 得到三个链表,递归左边和右边链表 left->next = mid->next = right->next = nullptr; lhead->next = quickSortList(lhead->next); rhead->next = quickSortList(rhead->next); // 拼接链表 getTail(lhead)->next = mhead->next; getTail(mhead)->next = rhead->next; auto re = lhead->next; delete lhead; delete mhead; delete rhead; return re; } };
#include <iostream> using namespace std; struct ListNode { int val; ListNode *next; ListNode(int x) : val(x) , next(NULL) { } }; // create linked list, -1 means NULL ListNode *createList() { int d; cin >> d; if (d == -1) return NULL; ListNode *head = new ListNode(d); head->next = createList(); return head; } ListNode *getTail(ListNode *head) { while (head->next) head = head->next; return head; } ListNode *quickSortList(ListNode *head) { // 遍历链表,按照三种情况分别加到三个链表中 // 空结点或单结点 if (!head || !head->next) return head; ListNode *lhead = new ListNode(-1), *mhead = new ListNode(-1), *rhead = new ListNode(-1); auto left = lhead, mid = mhead, right = rhead; // 遍历链表 int x = head->val; for (auto p = head; p; p = p->next) { if (p->val < x) left = left->next = p; else if (p->val == x) mid = mid->next = p; else right = right->next = p; } // 得到三个链表,递归左边和右边链表 left->next = mid->next = right->next = nullptr; lhead->next = quickSortList(lhead->next); rhead->next = quickSortList(rhead->next); // 拼接链表 getTail(lhead)->next = mhead->next; getTail(mhead)->next = rhead->next; auto re = lhead->next; delete lhead; delete mhead; delete rhead; return re; } int main() { auto head = createList(); head = quickSortList(head); while (head) { cout << head->val << " "; head = head->next; } return 0; }
写在最后:我的博客主要是对计算机领域所学知识的总结、回顾和思考,把每篇博客写得通俗易懂是我的目标,分享技术和知识是一种快乐 ,非常欢迎大家和我一起交流学习,有任何问题都可以在评论区留言,也期待与您的深入交流(^∀^●)
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。