165. Merge Two Sorted Lists

165. 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
Example 1:
Input: list1 = null, list2 = 0->3->3->null
Output: 0->3->3->null

Example 2:
Input: list1 = 1->3->8->11->15->null, list2 = 2->null
Output: 1->2->3->8->11->15->null

Main Idea:

Easy problem. The basic usage of dummy node.

Tips/Notes:

  1. Be careful about the node update and return node. Specific notice at comments.

Code:

/**
 * Definition of singly-linked-list:
 * class ListNode {
 * public:
 *     int val;
 *     ListNode *next;
 *     ListNode(int val) {
 *        this->val = val;
 *        this->next = NULL;
 *     }
 * }
 */

class Solution {
public:
    /**
     * @param l1: ListNode l1 is the head of the linked list
     * @param l2: 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 = new ListNode(-1);
        ListNode* tmp = dummy;
        while(l1 || l2){
        	// check if there is only l2
            if(l1 == nullptr){
                tmp->next = l2;
                //notice: don't forget to return the result
                return dummy->next;
            }
            // check whether there is only l1
            if(l2 == nullptr){
                tmp->next = l1;
                return dummy->next;
            }
            
            // comparision to update the node.
            if(l1->val <= l2->val){
                tmp->next = l1;
                // notice: don't forget to update the node
                tmp = tmp->next;
                l1 = l1->next;
            }
            else{
                tmp->next = l2;
                tmp = tmp->next;
                l2 = l2->next;
            }
        }
        return dummy->next;
    }
};
发布了28 篇原创文章 · 获赞 1 · 访问量 431

猜你喜欢

转载自blog.csdn.net/Zahb44856/article/details/104058256
今日推荐