- 描述
- 示例
- 算法思想
- 代码
1 /** 2 * Definition for singly-linked list. 3 * struct ListNode { 4 * int val; 5 * ListNode *next; 6 * ListNode(int x) : val(x), next(NULL) {} 7 * }; 8 */ 9 class Solution { 10 public: 11 //合并两个链表 12 ListNode* merge(ListNode* pHead1, ListNode* pHead2) { 13 ListNode* pre = nullptr; 14 ListNode* p = pHead1; 15 ListNode* q = pHead2; 16 //特殊情况判断 17 if (pHead1 == nullptr) return pHead2; 18 if (pHead2 == nullptr) return pHead1; 19 //L2合并至L1 20 if (q->val >= p->val) { 21 while (p && q) { 22 if (q->val >= p->val) { 23 pre = p; 24 p = pre->next; 25 } else { 26 ListNode* r = q->next; 27 q->next = p; 28 pre->next = q; 29 pre = q; 30 q = r; 31 } 32 } 33 34 if (q) { 35 pre->next = q; 36 } 37 return pHead1; 38 } else { //L1合并至L2 39 while (p && q) { 40 if (p->val >= q->val) { 41 pre = q; 42 q = pre->next; 43 } else { 44 ListNode* r = p->next; 45 p->next = q; 46 pre->next = p; 47 pre = p; 48 p = r; 49 } 50 } 51 if (p) { 52 pre->next = p; 53 } 54 return pHead2; 55 } 56 } 57 // 分治进行链表两两合并 58 ListNode* mergeList(vector<ListNode*>& lists, int l, int r) { 59 60 if (l == r) return lists[l]; 61 if (l > r) return nullptr; 62 63 int mid = (l + r) / 2; 64 65 return merge(mergeList(lists, l, mid), mergeList(lists, mid + 1, r)); 66 } 67 68 ListNode* mergeKLists(vector<ListNode*>& lists) { 69 //采用分治法进行合并 70 return mergeList(lists, 0, lists.size() - 1); 71 } 72 };
标签:pre,ListNode,val,合并,next,链表,return,排序 From: https://www.cnblogs.com/yueshengd/p/17376988.html