How to Sort a Linked List by Converting to Array/Vector?

  • Time:2020-09-12 10:06:27
  • Class:Weblog
  • Read:17

Although, sorting a linked list can be done via Recursive Divide-and-Conquer algorithm i.e. merge sorting, we can however, turn the linked list into an array (or vector) using O(N) time and space, then sort the array/vector in O(nlogn), and finally convert it back to the linked list in O(n) time.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* insertionSortList(ListNode* head) {
        if (head == NULL) return NULL;
        vector<int> data;
        ListNode *p = head;
        while (p) {
            data.push_back(p->val);
            p = p->next;
        }
        sort(begin(data), end(data));
        p = head;
        for (const auto &n: data) {
            p->val = n;
            p = p->next;
        }
        return head;
    }
};
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* insertionSortList(ListNode* head) {
        if (head == NULL) return NULL;
        vector<int> data;
        ListNode *p = head;
        while (p) {
            data.push_back(p->val);
            p = p->next;
        }
        sort(begin(data), end(data));
        p = head;
        for (const auto &n: data) {
            p->val = n;
            p = p->next;
        }
        return head;
    }
};

We don’t need to allocate new nodes for the sorted singly-linked list. Instead, we can follow the original linked list in the same order of the sorted array, then synchronise the values from the array to the linked list. This will cost O(N) time and O(1) additional space.

–EOF (The Ultimate Computing & Technology Blog) —

Recommend:
What is Cycle Counting and How to Implement It in Your Retail Bu
4 Reasons Why Your Blog is Struggling to Find an Audience
6 Best Fashion Bloggers for Style Inspiration
The Strategy You Need to Write Better Blog Posts Than Your Compe
How to Improve Your Blog’s Bounce Rate (and Why You Should)
Does Your SME Have A Disaster Recovery Plan?
7 Best SEO Trends Gaining Popularity In 2019
How To Choose The Best Hosting Service For A WordPress Website
An Idiot’s Guide to Email Automation for Bloggers
Checklist for Choosing a Perfect WordPress Blog Theme
Share:Facebook Twitter
Comment list
Comment add