jayati

Merge k Sorted Lists

Jan 29th, 2023
195
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.61 KB | None | 0 0
  1. /**
  2.  * Definition for singly-linked list.
  3.  * struct ListNode {
  4.  *     int val;
  5.  *     ListNode *next;
  6.  *     ListNode() : val(0), next(nullptr) {}
  7.  *     ListNode(int x) : val(x), next(nullptr) {}
  8.  *     ListNode(int x, ListNode *next) : val(x), next(next) {}
  9.  * };
  10.  */
  11. class Solution {
  12.  
  13. ListNode* joinLinkedLists(vector<ListNode*>& lists) {
  14.     ListNode* head = nullptr;
  15.     ListNode* tail = nullptr;
  16.  
  17.     // Iterate through all linked lists in the vector
  18.     for (auto& list : lists) {
  19.         if (list == nullptr) continue;
  20.         if (head == nullptr) {
  21.             head = list;
  22.             tail = list;
  23.         }
  24.         else {
  25.             tail->next = list;
  26.             tail = list;
  27.         }
  28.         while (tail->next) tail = tail->next;
  29.     }
  30.  
  31.     return head;
  32. }
  33. // Function to sort a linked list
  34. void sortLinkedList(ListNode*& head) {
  35.     if (head == nullptr || head->next == nullptr) return;
  36.  
  37.     // Initialize an empty vector
  38.     vector<int> values;
  39.  
  40.     // Traverse the linked list and store the values in the vector
  41.     ListNode* current = head;
  42.     while (current) {
  43.         values.push_back(current->val);
  44.         current = current->next;
  45.     }
  46.  
  47.     // Sort the vector
  48.     sort(values.begin(), values.end());
  49.  
  50.     // Traverse the linked list again and update the values
  51.     current = head;
  52.     for (int val : values) {
  53.         current->val = val;
  54.         current = current->next;
  55.     }
  56. }
  57.  
  58. public:
  59.     ListNode* mergeKLists(vector<ListNode*>& lists) {
  60.     ListNode* head = joinLinkedLists(lists);
  61.  
  62.     sortLinkedList(head);
  63.     return head;
  64.        
  65.        
  66.     }
  67. };
Advertisement
Add Comment
Please, Sign In to add comment