Leetcode: 21. Merge Two Sorted Lists

Description

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.

思路

  • 合并两个有序链表,这个没啥好说的吧

代码

/**
 * 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) {
        ListNode *head = NULL, *ptr = NULL, *tmp;
        
        while(l1 && l2){
            if(l1->val > l2->val){
                tmp = l2;
                l2 = l2->next;
            }
            else{
                tmp = l1;
                l1 = l1->next;
            }
            
            if(!head)
                head = ptr = tmp;
            else{
                ptr->next = tmp;
                ptr = ptr->next;
            }
        }
        
        if(l1){
            if(!head)
                    head = ptr = l1;
                else ptr->next = l1;
        }
        
        if(l2){
             if(!head)
                    head = ptr = l2;
                else ptr->next = l2;
        }
        
        return head;
    }
};
posted @ 2017-05-07 21:19  JeffLai  阅读(105)  评论(0编辑  收藏  举报