I was solving Leetcode question 23, the aim is to merge k sorted lists. The input is a vector of starting Listnodes of those k lists. I wanted to extract the size of this vector for my for loop but the inbuilt size function is giving random large integers as output.
Also, an interesting observation: When I uncomment line 72, in int main() (cout<<lists.size()<<endl;) the code works as intended.
#include<bits/stdc++.h>
using namespace std;
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 {
public:
ListNode* mergeKLists(vector<ListNode*>& lists) {
ListNode* dummy;
ListNode* output;
output->next = dummy;
ListNode* final_output = output;
int empty_count = 0;
auto size = lists.size();
cout<<typeid(size).name()<<endl;
bool flag = true;
while(flag){
int current_min = INT_MAX;
int min_index = 0;
flag = false;
for(int i = 0; i<lists.size(); i++){
if(lists[i] != nullptr){
flag = true;
if(lists[i]->val < current_min){
current_min = lists[i]->val;
min_index = i;
}
}
}
if(flag==false){break;}
output->next = lists[min_index];
output = output->next;
lists[min_index] = lists[min_index]->next;
}
return final_output->next;
}
};
int main(){
ListNode* list1;
ListNode* list2;
ListNode* list3;
ListNode* list4;
list1 = new ListNode(1);
list1->next = new ListNode(4);
list1->next->next = new ListNode(5);
list2 = new ListNode(1);
list2->next = new ListNode(3);
list2->next->next = new ListNode(4);
list3 = new ListNode(2);
list3->next = new ListNode(6);
vector<ListNode*> lists;
lists.push_back(list1);
lists.push_back(list2);
lists.push_back(list3);
// cout<<lists.size()<<endl;
Solution obj;
ListNode* ans = obj.mergeKLists(lists);
while(ans){
cout<<ans->val<<" ";
ans = ans->next;
}
return 0;
}
I tried checking for the typeid name of size variable. It was ‘j’. I do not understand what this means aswell.
Kunal Randad is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.