21. Merge Two Sorted Lists

来源:互联网 发布:英文翻译什么软件好 编辑:程序博客网 时间:2024/06/07 19:28

题目原文

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.


代码

class Solution {public:    ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {        if(!l1&&!l2) return NULL;        if(!l1&&l2) return l2;        if(l1&&!l2) return l1;        ListNode* start,*cur;        if(l1->val<l2->val){            start=l1;            cur=start;            l1=l1->next;        }        else{            start=l2;            cur=start;            l2=l2->next;        }        for(;l1&&l2;){            if(l1->val<l2->val){                cur->next=l1;                l1=l1->next;                cur=cur->next;            }            else{                cur->next=l2;                l2=l2->next;                cur=cur->next;            }        }        if(l1) cur->next=l1;        if(l2) cur->next=l2;        return start;    }};
0 0
原创粉丝点击