LintCode-165 · 合并两个排序链表-题解

描述:
将两个排序(升序)链表合并为一个新的升序排序链表

样例 1:
输入: list1 = null, list2 = 0->3->3->null
输出: 0->3->3->null
样例2:
输入:  list1 =  1->3->8->11->15->null, list2 = 2->null
输出: 1->2->3->8->11->15->null

解题思路:
先对特殊情况进行判断,再创建一个指针p用来接收两个链表的头节点中较小的那一个,然后将这个链表的next和另一个链表再次递归下去。

AC代码如下:

/**
 * 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
        if(!l1 && l2) return l2;
        else if(l1 && !l2) return l1;
        else if(!l1 && !l2) return NULL;
        ListNode *p;
        if(l1->val < l2->val){
            p=l1;
            p->next=mergeTwoLists(l1->next,l2);
        }
        else{
            p=l2;
            p->next=mergeTwoLists(l1,l2->next);
        }
        return p;
    }
};

上一篇:【性能】web提升性能的小总结


下一篇:562 -背包问题IV - LintCode