Insertion Sort List

Sort a linked list using insertion sort.

Algorithm of Insertion Sort:

  1. Insertion sort iterates, consuming one input element each repetition, and growing a sorted output list.

  2. At each iteration, insertion sort removes one element from the input data, finds the location it belongs within the sorted list, and inserts it there.

  3. It repeats until no input elements remain.

Example 1:


Input: 4->2->1->3
Output: 1->2->3->4

Example 2:


Input: -1->5->3->4->0
Output: -1->0->3->4->5

Solutions

🧠 Cpp

class Solution
{
    ListNode* insert(ListNode *root, int val)
    {
        ListNode *new_node = new ListNode(val),
                 *head = root;
        if(head->val > val)
        {
            new_node->next = head;
            return new_node;
        }

        while(head->next != nullptr && head->next->val < val)
            head = head->next;

        ListNode *tmp = head->next;
        head->next = new_node;
        new_node->next = tmp;

        return root;
    }

public:
    ListNode* insertionSortList(ListNode *head)
    {
        if(!head || !head->next)
            return head;

        //allocate sorted list
        ListNode *new_root =  new ListNode(head->val);

        for(ListNode *elem = head->next; elem; elem = elem->next)
        {
            new_root = insert(new_root, elem->val);
        }

        return new_root;
    }
};

Last updated