标签:logs for init short val ase class result return
/** * 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) { // head1为空,返回head2 if(l1 == NULL) return l2; // head2为空,返回head1 if(l2 == NULL) return l1; // 记录合并链表 ListNode *node = NULL; if(l1->val > l2->val) { node = l2; node->next = mergeTwoLists(l1, l2->next); } else { node = l1; node->next = mergeTwoLists(l1->next, l2); } return node; } };
当然也可以在原链表的基础上面直接合并。
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode *node = NULL; ListNode *mergeKLists(vector<ListNode *> &lists) { if (lists.size() < 1) return NULL; while (lists.size()-1){ lists.push_back(mergeTwoLists(lists[0], lists[1])); lists.erase(lists.begin()); lists.erase(lists.begin()); } return lists.front(); } ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) { // head1为空,返回head2 if(l1 == NULL) return l2; // head2为空,返回head1 if(l2 == NULL) return l1; // 记录合并链表 if(l1->val > l2->val) { l2->next = mergeTwoLists(l1, l2->next); return l2; } else { l1->next = mergeTwoLists(l1->next, l2); return l1; } } };
标签:logs for init short val ase class result return
原文地址:http://www.cnblogs.com/Kobe10/p/6363321.html