LeetCode 21. Merge Two Sorted Lists

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

/**
 * 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 *s;
        s = new ListNode(0);
        ListNode *t1, *t2, *t;
        t1 = l1; t2 =l2; t = s;
        while(t1!=NULL && t2!=NULL){
            if(t1->val<=t2->val){
                t->next = t1;
                t1=t1->next;
            }else{
                t->next = t2;
                t2= t2->next;
            }
            t = t->next;
        }
        if(t1!=NULL)
            t->next = t1;
        if(t2!=NULL)
            t->next = t2;
        ListNode *ans;
        ans = s->next;
        delete s;
        return ans;
    }
};
原文地址:https://www.cnblogs.com/A-Little-Nut/p/9834728.html