标签:cto private lis problem tor nbsp ptr nullptr 题目
题目地址:https://leetcode-cn.com/problems/merge-k-sorted-lists/
解题思路:简单的分治算法
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { private: ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) { ListNode *Head=new ListNode(0); ListNode *p,*q,*h; p=l1; q=l2; h=Head; while(p&&q){ if(p->val>=q->val){ h->next=q; h=h->next; q=q->next; } else{ h->next=p; h=h->next; p=p->next; } } if(p) h->next=p; else h->next=q; return Head->next; } ListNode *merge(vector<ListNode*>& lists,int l,int r){ if (l == r) return lists[l]; if (l > r) return nullptr; int mid = (l + r) >> 1; return mergeTwoLists(merge(lists, l, mid), merge(lists, mid + 1, r)); } public: ListNode* mergeKLists(vector<ListNode*>& lists) { return merge(lists,0,lists.size()-1); } };
标签:cto private lis problem tor nbsp ptr nullptr 题目
原文地址:https://www.cnblogs.com/cc-xiao5/p/13502003.html