LeetCode_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.

将两个有序链表合为一个有序的链表并返回头指针。

/**
 * 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 *result;
        if(l1==NULL)return l2;
        if(l2==NULL)return l1;
        if(l1->val<=l2->val)result = l1;
        else result = l2;
        ListNode *r;
        while(l1!=NULL&&l2!=NULL)
        {
           int flag=0;
           while(l1!=NULL&&l2!=NULL&&l1->val<=l2->val)
           {
             r = l1;
             l1 = l1->next;
             flag = 1;
           }
           if(flag == 1)
           {
             r->next = l2;
             r = r->next;
             l2 = l1;
             l1 = r;
           }
           
          while(l1!=NULL&&l2!=NULL&&l1->val>=l2->val)
           {
             r = l2;
             l2 = l2->next;
             flag = 2;
           }
           if(flag == 2)
           {
             r->next = l1;
             r = r->next;
             l1 = l2;
             l2 = r;
           }
        }
        return result;
    }
};


原文地址:https://www.cnblogs.com/sunp823/p/5601443.html