您的位置:首页 > 其它

LeetCode: Merge Two Sorted Lists

2014-06-25 14:39 211 查看
思路:基本的合并两个有序链表,注意边界条件的处理即可。注意题目中的要求,原链表上整合两条链表,所以不要额外开辟一个新节点链表。

code:

class Solution {
public:
ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) {
ListNode *h, *cur;
if(l1 == NULL || l2 == NULL)return l1 == NULL ? l2 : l1;
if(l1->val < l2->val){
h = cur = l1;
l1 = l1->next;
}
else{
h = cur = l2;
l2 = l2->next;
}
while(l1 && l2){
if(l1->val < l2->val){
cur->next = l1;
cur = l1;
l1 = l1->next;
}
else{
cur->next = l2;
cur = l2;
l2 = l2->next;
}
}
if(l1)cur->next = l1;
if(l2)cur->next = l2;
return h;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: