LeetCode——合并两个有序链表

 

/**
 * 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 *l3 = new ListNode(0), *l4 = l3;
        int x,y;
        while(l1!=NULL | l2 !=NULL)
        {
            if(l1 != NULL)
                x = l1->val;
            else
            {
                l3->next = l2;
                break; 
            }
            if(l2 != NULL)
                y = l2->val;
            else
            {
                l3->next = l1;
                break;
            }
            if(x >= y)
            {
                l3->next = new ListNode(y);
                l2 = l2->next; 
            }
            else
            {
                l3->next = new ListNode(x);
                l1 = l1->next; 
            }
            l3 = l3->next;
        }
        return l4->next;
    }
};

猜你喜欢

转载自blog.csdn.net/goldcarpenter/article/details/82915750