leetcode 21. 合并两个有序链表

leetcode

C++:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
        
        ListNode *head = NULL;
        ListNode *node = NULL;
        while ( l1 || l2 ) {

            if ( l1 && l2 ) {

                if ( l1 -> val > l2 -> val ) {

                    if ( node ) {

                        node -> next = l2;
                        node = node -> next;
                        
                    } else {

                        node = l2;
                    }
                    l2 = l2 -> next;
                    node -> next = NULL;

                } else if ( l1 -> val < l2 -> val ) {

                    if ( node ) {

                        node -> next = l1;
                        node = node -> next;
                        
                    } else {

                        node = l1;
                    }
                    l1 = l1 -> next;
                    node -> next = NULL;

                } else {

                    // if ( l1 -> val == l2 -> val )
                    if ( node ) {

                        node -> next = l1;
                        node = node -> next;
                        
                    } else {

                        node = l1;
                    }
                    l1 = l1 -> next;

                    if ( !head && node ) {

                        head = node;
                    }

                    node -> next = l2;
                    l2 = l2 -> next;
                    node = node -> next;
                    node -> next = NULL;
                }

            } else if ( l1 ) {

                if ( node ) {

                    node -> next = l1;
                    node = node -> next;
                    
                } else {

                    node = l1;
                }
                l1 = l1 -> next;
                node -> next = NULL;

            } else {

                // if ( l2 )
                if ( node ) {

                    node -> next = l2;
                    node = node -> next;
                    
                } else {

                    node = l2;
                }
                l2 = l2 -> next;
                node -> next = NULL;
            }

            if ( !head && node ) {

                head = node;
            }
        }

        return head;
    }
};

你可能感兴趣的:(leetcode 21. 合并两个有序链表)