标签:leetcode merge two sorted lis
题目链接:https://leetcode.com/problems/merge-two-sorted-lists/
题目:Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.
解题报告:两个链表L1,L2。(1)L1->val > L2->val ,那么L2的数字插入L1中。在L1->next->val中找出比L2->val值大的数,那就插入L2->val。
(2)L2->val
> L1->val ,那么L1的数字插入L2中。在L2->next->val中找出比L1->val值大的数,那就插入L1->val。
class Solution { public: ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) { if(l1 == NULL) return l2; if(l2 == NULL) return l1; ListNode *answers ,*t; if (l1->val < l2->val) { answers = l1; for ( ; l2->next != NULL; l2 = t) { t = l2->next; for ( ; l1->next != NULL; l1 = l1->next) if ( l1->next->val > l2->val) break; l2->next = l1->next; l1->next = l2; } for ( ; l1->next != NULL; l1 = l1->next) if ( l1->next->val > l2->val) break; l2->next = l1->next; l1->next = l2; } else { answers = l2; for ( ; l1->next != NULL; l1 = t) { t = l1->next; for ( ; l2->next != NULL; l2 = l2->next) if ( l2->next->val > l1->val) break; l1->next = l2->next; l2->next = l1; } for ( ; l2->next != NULL; l2 = l2->next) if ( l2->next->val > l1->val) break; l1->next = l2->next; l2->next = l1; } return answers; } };
LeetCode_Merge Two Sorted Lists
标签:leetcode merge two sorted lis
原文地址:http://blog.csdn.net/vanish_dust/article/details/44150611