Merge Two Sorted Lists

Description

Merge two sorted (ascending) linked lists and return it as a new sorted list. The new sorted list should be made by splicing together the nodes of the two lists and sorted in ascending order.

Example
Given 1->3->8->11->15->null, 2->null , 
return 1->2->3->8->11->15->null.

Lintcode_ladder

Method

  1. x
  2. x

Example

  1. 1
/**
 * Definition of ListNode
 * class ListNode {
 * public:
 *     int val;
 *     ListNode *next;
 *     ListNode(int val) {
 *         this->val = val;
 *         this->next = NULL;
 *     }
 * }
 */
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) {
        // write your code here
        ListNode dummy(0);
        ListNode* tail = &dummy;
        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) {
        //     while (l1) {
        //       tail->next = l1;
        //       l1 = l1->next;
        //       tail = tail->next;
        //     }
        // } else {
        //     while (l2) {
        //       tail->next = l2;
        //       l2 = l2->next;
        //       tail = tail->next;
        //     }
        // }
        if (l1) {
            tail->next = l1; 
        } else {
            tail->next = l2;
        }
        return dummy.next;
    }
};

Similar problems

x

Tags

x

results matching ""

    No results matching ""