LeetCode 23 Merge k Sorted Lists,28ms beats 99% cpp.

1. 首先写出两个排序链表的函数
2. 然后两两进行调用上述函数即可

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* mergeTwoLists(ListNode* l1,ListNode* l2) {
        ListNode preHead(0),*p=&preHead;
        while(l1&&l2) {
            if (l1->val<l2->val) {
                p->next=l1;
                l1=l1->next;
            }
            else {
                p->next=l2;
                l2=l2->next;
            }
            p=p->next;
        }
        p->next=l1 ? l1:l2;
        return preHead.next;
    }
    ListNode* mergeKLists(vector<ListNode*>& lists) {
        int len=lists.size();
        if (len==0) return NULL;
        for (int i=1;i<len;i*=2)
            for (int j=0;j<len-i;j+=2*i)
                lists[j]=mergeTwoLists(lists[j],lists[j+i]);
        return lists[0];
    }
};

你可能感兴趣的:(LeetCode 23 Merge k Sorted Lists,28ms beats 99% cpp.)