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;
    }
};

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,768评论 0 33
  • //leetcode中还有花样链表题,这里几个例子,冰山一角 求单链表中结点的个数----时间复杂度O(n)这是最...
    暗黑破坏球嘿哈阅读 1,533评论 0 6
  • 花2天把Leetcode上Linked lists的题目刷完了,下面是一些我觉得比较有倾诉欲望的题。 237. D...
    __小赤佬__阅读 619评论 0 1
  • I don't have much requirements about mobile phones. If it...
    Donutzpj阅读 135评论 0 0
  • 最近也不知怎么地,异常的烦躁,心里想着乱七八糟的事。明明知道这样不对,但就是沉不下心来。或许是自己想的太多!每...
    小资w阅读 205评论 0 0