Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * Definition for singly-linked list.
- * struct ListNode {
- * int val;
- * ListNode *next;
- * ListNode() : val(0), next(nullptr) {}
- * ListNode(int x) : val(x), next(nullptr) {}
- * ListNode(int x, ListNode *next) : val(x), next(next) {}
- * };
- */
- class Solution {
- ListNode* joinLinkedLists(vector<ListNode*>& lists) {
- ListNode* head = nullptr;
- ListNode* tail = nullptr;
- // Iterate through all linked lists in the vector
- for (auto& list : lists) {
- if (list == nullptr) continue;
- if (head == nullptr) {
- head = list;
- tail = list;
- }
- else {
- tail->next = list;
- tail = list;
- }
- while (tail->next) tail = tail->next;
- }
- return head;
- }
- // Function to sort a linked list
- void sortLinkedList(ListNode*& head) {
- if (head == nullptr || head->next == nullptr) return;
- // Initialize an empty vector
- vector<int> values;
- // Traverse the linked list and store the values in the vector
- ListNode* current = head;
- while (current) {
- values.push_back(current->val);
- current = current->next;
- }
- // Sort the vector
- sort(values.begin(), values.end());
- // Traverse the linked list again and update the values
- current = head;
- for (int val : values) {
- current->val = val;
- current = current->next;
- }
- }
- public:
- ListNode* mergeKLists(vector<ListNode*>& lists) {
- ListNode* head = joinLinkedLists(lists);
- sortLinkedList(head);
- return head;
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment