LeetCode-21 Merge Two Sorted Lists

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_30986521/article/details/80932158

题目链接

链表合并,注意细节

/**
 * 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 *p = l1, *q = l2, *newlist_head = NULL, *rear, *temp;
        
        while (p != NULL && q != NULL)
        {
            int x = p->val, y = q->val;
            
            if (x < y)
            {
                temp = new ListNode(x);
                p = p->next;
            }
            else
            {
                temp = new ListNode(y);
                q = q->next;
            }
            
            if (newlist_head == NULL)
            {
                newlist_head = temp;
                rear = temp;
            }
            else
            {
                rear->next = temp;
                rear = temp;
            }
        }
        
        if (p != NULL)
        {
            if (newlist_head == NULL)
                newlist_head = p;
            else
                rear->next = p;
        }
        else
        {
            if (newlist_head == NULL)
                newlist_head = q;
            else
                rear->next = q;
        }
        
        return newlist_head;
    }
};

猜你喜欢

转载自blog.csdn.net/qq_30986521/article/details/80932158