
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Sort List in C++
Suppose we have a list, we have to sort this in O(n logn) time using constant space complexity, so if the list is like [4,2,1,3], then it will be [1,2,3,4]
To solve this, we will follow these steps −
Define a method for merging two lists in sorted, order, that method is merge(), this takes two lists l1 and l2.
The sort list method will work like below −
if head is null, or next of head is null, then return head
slow := head, fast := head, and prev = null
-
while fast is not null and next of fast is also not null, do
prev := slow
slow := next of slow
fast := next of next of fast
next of prev := null
l1 := sortList(head)
l2 := sortList(slow)
return merge(l1, l2)
Let us see the following implementation to get better understanding −
Example
#include <bits/stdc++.h> using namespace std; class ListNode{ public: int val; ListNode *next; ListNode(int data){ val = data; next = NULL; } }; ListNode *make_list(vector<int> v){ ListNode *head = new ListNode(v[0]); for(int i = 1; i<v.size(); i++){ ListNode *ptr = head; while(ptr->next != NULL){ ptr = ptr->next; } ptr->next = new ListNode(v[i]); } return head; } void print_list(ListNode *head){ ListNode *ptr = head; cout << "["; while(ptr){ cout << ptr->val << ", "; ptr = ptr->next; } cout << "]" << endl; } class Solution { public: ListNode* sortList(ListNode* head) { if(!head || !head->next)return head; ListNode *slow = head, *fast = head, *prev = NULL; while(fast && fast->next){ prev = slow; slow = slow->next; fast = fast->next->next; } prev->next = NULL; ListNode* l1 = sortList(head); ListNode* l2 = sortList(slow); return mergeList(l1,l2); } ListNode* mergeList(ListNode* l1, ListNode* l2){ ListNode* temp = new ListNode(0); ListNode* p =temp; while(l1 && l2){ if(l1->val<=l2->val){ p->next = l1; l1 = l1->next; }else{ p->next = l2; l2 = l2->next; } p = p->next; } if(l1){ p->next = l1; } if(l2){ p->next = l2; } return temp->next; } }; main(){ vector<int> v = {4,2,1,3,5,19,18,6,7}; ListNode *h1 = make_list(v); Solution ob; print_list((ob.sortList(h1))); }
Input
[4,2,1,3,5,9,8,6,7]
Output
[1, 2, 3, 4, 5, 6, 7, 18, 19, ]
Advertisements