先贴代码:
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode* mergeKLists(vector<ListNode*>& lists) { ListNode *pNewList = mergeCore(lists); return pNewList; } ListNode* mergeCore(vector<ListNode*>& lists) { if (lists.empty()) return nullptr; if (lists.size() == 1) return lists[0]; int nMin = 100; vector<ListNode *>::iterator iter = lists.begin(); vector<ListNode *>::iterator iterMin; while(iter != lists.end()) { if (*iter == nullptr) { iter = lists.erase(iter); } else { if ((*iter)->val <= nMin) { iterMin = iter; nMin = (*iter)->val; } ++iter; } } if (lists.empty()) return nullptr; ListNode *pMinNode = *iterMin;
(*iterMin) = (*iterMin)->next;
pMinNode->next = mergeCore(lists); return pMinNode; } };
方法:使用递归,可读性强,已于书写。
关键:使用iterator来编译整个过程中,不要忘记处理++iter,以及iter = lists.erase(iter)更新索引。
在找到最小值之后,需要在vector中更新指针索引,将相应最小值的指针指向下一个节点。
递归处理的奥义是:设置一个指针,更新该指针之后,要需要将该指针的next指向递归函数体,最后是返回该指针,最终实现递归处理。