【面試】單鏈表排序,時間複雜度O(nlogn)、空間複雜度O(1)

(1)如果不要求空間複雜度,則可以將鏈表元素存至vectorvector,排序後將其化爲鏈表

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
struct ListNode {
    int val;
    ListNode* next;
    ListNode(int x) : val(x), next(NULL) {}
};
int main() {
	int n;
	cin >> n;
	vector<int> ans(n);
	for (int i = 0; i < n; ++i) {
		cin >> ans[i];
	}
	sort(ans.begin(), ans.end());
	ListNode *head = new ListNode(0);
    ListNode *cur = head;
    for (int i = 0; i < n; ++i) {
        ListNode *temp = new ListNode(ans[i]);
        cur->next = temp;
        cur = temp;
    }
    head = head->next;
    while (head) {
    	if (head->next) cout << head->val << "->";
    	else cout << head->val << endl;
    	head = head->next;
    }
    return 0;
}

(2) 現在要求空間複雜度爲O(1)O(1),那麼我們可以採用歸併排序進行處理

  • 使用快慢指針找到中間節點,然後遞歸進行歸併
#include <iostream>
using namespace std;
struct ListNode {
    int val;
    ListNode* next;
    ListNode(int x) : val(x), next(NULL) {}
};

ListNode *Merge(ListNode* left, ListNode* right) {
    if (left == nullptr && right == nullptr) return nullptr;
    ListNode p(0);
    ListNode *h = &p;
    while (left && right) {
        if (left->val < right->val) {h->next = left; left = left->next;}
        else {h->next = right; right = right->next;}
        h = h->next;
    }
    if (left && !right) h->next = left;
    if (!left && right) h->next = right;
    return p.next;
}

ListNode *SortList(ListNode *head) {
    if (head == nullptr || head->next == nullptr) return head;
    ListNode *fast = head->next;
    ListNode *slow = head;
    while (fast && fast->next) {
        slow = slow->next;
        fast = fast->next->next;
    }

    ListNode *left = SortList(slow->next);
    slow->next = nullptr;
    ListNode *right = SortList(head);
    return Merge(left, right);
}

int main() {
    int n;
    cin >> n;
    ListNode *head = new ListNode(0);
    ListNode *cur = head;
    for (int i = 0; i < n; ++i) {
        int num;
        cin >> num;
        ListNode *temp = new ListNode(num);
        cur->next = temp;
        cur = temp;
    }
    head = SortList(head->next);
    while (head) {
        if (head->next)
            cout << head->val << "->";
        else 
            cout << head->val;
        head = head->next;
    }
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章