[Cpp]
Struct ListNode {
Int val;
ListNode * next;
ListNode (int x): val (x), next (NULL ){}
};
Class Solution {
// O (nlogk)
// Using priority_queue to choose current minimum node
// Node: keep priority_queue free of NULL pointer
Public:
Struct PQNode
{
Int index;
ListNode * ptr;
PQNode (int _ index = 0, ListNode * _ ptr = NULL): index (_ index), ptr (_ ptr ){}
};
Struct Comp
{
Bool operator () (const PQNode & lhs, const PQNode & rhs) const
{
Return lhs. ptr-> val> rhs. ptr-> val;
}
};
ListNode * mergeKLists (vector <ListNode *> & lists ){
// Start typing your C/C ++ solution below
// Do not write int main () function
Priority_queue <PQNode, vector <PQNode>, Comp> pq;
ListNode * head = NULL;
ListNode * cur = NULL;
Do
{
For (int I = 0; I <lists. size (); ++ I)
{
If (lists [I]! = NULL)
{
Pq. push (PQNode (I, lists [I]);
Lists [I] = lists [I]-> next;
}
}
If (pq. empty () break;
If (head = NULL)
Head = pq. top (). ptr;
Else
Cur-> next = pq. top (). ptr;
Cur = pq. top (). ptr;
Int curIdx = pq. top (). index;
Pq. pop ();
If (lists [curIdx]! = NULL)
{
Pq. push (PQNode (curIdx, lists [curIdx]);
Lists [curIdx] = lists [curIdx]-> next;
}
} While (true );
If (cur! = NULL) cur-> next = NULL;
Return head;
}
};
Struct ListNode {
Int val;
ListNode * next;
ListNode (int x): val (x), next (NULL ){}
};
Class Solution {
// O (nlogk)
// Using priority_queue to choose current minimum node
// Node: keep priority_queue free of NULL pointer
Public:
Struct PQNode
{
Int index;
ListNode * ptr;
PQNode (int _ index = 0, ListNode * _ ptr = NULL): index (_ index), ptr (_ ptr ){}
};
Struct Comp
{
Bool operator () (const PQNode & lhs, const PQNode & rhs) const
{
Return lhs. ptr-> val> rhs. ptr-> val;
}
};
ListNode * mergeKLists (vector <ListNode *> & lists ){
// Start typing your C/C ++ solution below
// Do not write int main () function
Priority_queue <PQNode, vector <PQNode>, Comp> pq;
ListNode * head = NULL;
ListNode * cur = NULL;
Do
{
For (int I = 0; I <lists. size (); ++ I)
{
If (lists [I]! = NULL)
{
Pq. push (PQNode (I, lists [I]);
Lists [I] = lists [I]-> next;
}
}
If (pq. empty () break;
If (head = NULL)
Head = pq. top (). ptr;
Else
Cur-> next = pq. top (). ptr;
Cur = pq. top (). ptr;
Int curIdx = pq. top (). index;
Pq. pop ();
If (lists [curIdx]! = NULL)
{
Pq. push (PQNode (curIdx, lists [curIdx]);
Lists [curIdx] = lists [curIdx]-> next;
}
} While (true );
If (cur! = NULL) cur-> next = NULL;
Return head;
}
};