Merge two sorted linked lists (C++)

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.

Remark:
链表可以加上tail指针,Java可以加个tail node 。
(感觉和指针差不多 比如 node1 是链表的第一个节点,下面的语句其实和 listNode *head = &node1 等价:
listNode head = node1;)

如此一来,不需要每次都从表头遍历一遍去到表尾,再把节点加到后面。

/**
 * 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 = new ListNode(0); //构造函数返回的居然是一个指针 
        ListNode *last = dummy;
        
        while (l1 && l2) {
            
            if (l1->val < l2->val) {
                
                last->next = l1;
                l1 = l1->next;
                
                last = last->next;
                
            } else {
                last->next = l2;
                l2 = l2->next;
                last = last->next;
            }
            
        }
        
        if (l1) {
            last->next = l1;
        }
        
        if (l2) {
            last->next = l2;
        }
        
        return dummy->next;
    }
};

你可能感兴趣的:(Merge two sorted linked lists (C++))