1. 程式人生 > 其它 >LintCode-165 · 合併兩個排序連結串列-題解

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