My C++ solution


  • 0
    X
    class Solution {
    public:
        /**
         * @param ListNode l1 is the head of the linked list
         * @param ListNode l2 is the head of the linked list
         * @return: ListNode head of linked list
         */
        ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) {
            ListNode *head = new ListNode(0);
            ListNode *tail = head;
            while (l1 && l2) {
                if (l1->val < l2->val) {
                    tail->next = l1;
                    l1 = l1->next;
                } else {
                    tail->next = l2;
                    l2 = l2->next;
                }
                tail = tail->next;
            }
            if (l1) {
                tail->next = l1;
            }
            if (l2) {
                tail->next = l2;
            }
            return head->next;
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.