【leetcode】Merge Two Sorted Lists
2015-01-26 23:25
274 查看
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.每次找到两个链表中小的一个,把他连接在后面,直到连接完成
思路1:利用递归方法解:递归思路:
if(l1->val<=l2->val)
{
head=l1;
head->next=mergeTwoLists(l1->next,l2);
}
else
{
head=l2;
head->next=mergeTwoLists(l1,l2->next);
}
class Solution { public: ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) { if(l1==NULL) { return l2; } if(l2==NULL) { return l1; } ListNode *head; if(l1->val<=l2->val) { head=l1; head->next=mergeTwoLists(l1->next,l2); } else { head=l2; head->next=mergeTwoLists(l1,l2->next); } return head; } };
非递归解法:
/** * 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) { if(l1==NULL) { return l2; } if(l2==NULL) { return l1; } ListNode *head=new ListNode(0); ListNode *pre=head; while(l1!=NULL||l2!=NULL) { if(l1==NULL) { head->next=l2; l2=l2->next; head=head->next; continue; } if(l2==NULL) { head->next=l1; l1=l1->next; head=head->next; continue; } if(l1->val<=l2->val) { head->next=l1; l1=l1->next; head=head->next; } else { head->next=l2; l2=l2->next; head=head->next; } } ListNode *ret=pre->next; delete pre; return pre->next; } };
相关文章推荐
- 25_leetcode_ Merge Two Sorted Lists
- leetcode-21 Merge Two Sorted Lists
- [Leetcode] Merge Two Sorted Lists
- LeetCode_OJ【21】Merge Two Sorted Lists
- leetcode 21: Merge Two Sorted Lists
- leetcode---merge-two-sorted-lists---链表
- [LeetCode][JavaScript]Merge Two Sorted Lists
- Leetcode-21:Merge Two Sorted Lists
- LeetCode小白菜笔记[7]:Merge Two Sorted Lists
- [LeetCode 21] Merge Two Sorted Lists Solution
- LeetCode 21.Merge Two Sorted Lists
- LeetCode Merge Two Sorted Lists
- 【LeetCode-easy】Merge Two Sorted Lists
- [Leetcode]Merge Two Sorted Lists
- LeetCode——merge-two-sorted-lists
- LeetCode--Merge Two Sorted Lists
- leetcode--Merge Two Sorted Lists
- LeetCode——Merge Two Sorted Lists
- [LeetCode] Merge Two Sorted Lists 合并两个有序链表
- LeetCode_Merge Two Sorted Lists