题解 | #合并有序链表#

合并有序链表

http://www.nowcoder.com/practice/a479a3f0c4554867b35356e0d57cf03d

class Solution {
public:
    ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
        if(l1 == nullptr) return l2;
        if(l2 == nullptr) return l1;
        ListNode* newHead = nullptr, *newEnd = nullptr;
        ListNode* getNode = nullptr;
        while(l1 && l2){
            getNode = l1->val < l2->val?l1:l2;
            getNode == l1?l1 = l1->next:l2 = l2->next;         
            !newHead?newHead = newEnd = getNode:newEnd=newEnd->next = getNode;
        }
        while(l1){
            newEnd = newEnd->next = l1;
            l1 = l1->next;
        }
        while(l2){
            newEnd = newEnd->next = l2;
            l2 = l2->next;
        }
        return newHead;
    }
};
全部评论

相关推荐

不愿透露姓名的神秘牛友
11-21 19:05
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务