Insertion Sort List
Input: 4->2->1->3
Output: 1->2->3->4
Input: -1->5->3->4->0
Output: -1->0->3->4->5Solutions
π§ Cpp
Last updated
Input: 4->2->1->3
Output: 1->2->3->4
Input: -1->5->3->4->0
Output: -1->0->3->4->5Last updated
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;
}
};