Leetcode 21 level 0


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.

Example:

Input: 1->2->4, 1->3->4
Output: 1->1->2->3->4->4
Note:

Very straight solution. Compare the top of each linked lists and pick the smaller one.

Code:

class Solution {
public:
    ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
        ListNode* ans=new ListNode(0);
        ListNode* now; now=ans; 
        while(l1!=NULL && l2!=NULL){
            ListNode* tmp;
            if(l1->val <= l2->val){
                tmp=l1;l1=l1->next;
            }
            else{
                tmp=l2;l2=l2->next;
            }
            now->next=tmp;
            now=now->next;
        }
        ListNode* remain;remain=l1;
        if(!remain)
            remain=l2;
        now->next=remain;
        return ans->next;
    }
};



阅读更多
个人分类: leetcode
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭
关闭