1. 程式人生 > >LeetCode#21: Merge Two Sorted Lists

LeetCode#21: Merge Two Sorted Lists

Description

Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.

Example

Example:

Input: 1->2->4, 1->3->4
Output: 1->1->2->3->4->4

Solution

這道題是一道比較經典的題目,要求合併兩個有序連結串列為一個新的有序連結串列。如果是在實際面試中出現的話,我們應當先問清楚是否可以修改原有連結串列。如果要求只在原有連結串列上進行合併的話,可以考慮使用遞迴的方式:

public class Solution {
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        if(l1 == null) return l2;
        if(l2 == null) return l1;
        
        ListNode head = null;
        if(l1.val < l2.val) {
        	head = l1;
        	head.next = mergeTwoLists(l1.next, l2);
        }
else { head = l2; head.next = mergeTwoLists(l1, l2.next); } return head; } }

但如果要求不可以修改原有連結串列,合併連結串列的每個節點都必須是新建立的話,則可以像歸併排序一般進行合併:

public class Solution2 {
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {    	
        ListNode head = new ListNode
(0); ListNode curr = head; while(l1 != null && l2 != null) { if(l1.val < l2.val) { curr.next = new ListNode(l1.val); l1 = l1.next; } else { curr.next = new ListNode(l2.val); l2 = l2.next; } curr = curr.next; } if(l1 == null) { while(l2 != null) { curr.next = new ListNode(l2.val); l2 = l2.next; curr = curr.next; } } else { while(l1 != null) { curr.next = new ListNode(l1.val); l1 = l1.next; curr = curr.next; } } return head.next; } }

而如果對是否可以修改原有連結串列不做要求,即可以修改原有連結串列也可以不修改,同時又沒有想出遞迴的方式,一般情況都能很容易地想到如下的方式:

public class Solution3 {
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {    	
        ListNode head = new ListNode(0);
        ListNode curr  = head;
        
        while(l1 != null && l2 != null) {
        	if(l1.val < l2.val) {
        		curr.next = new ListNode(l1.val);
        		l1 = l1.next;
        	} else {
        		curr.next = new ListNode(l2.val);
        		l2 = l2.next;
        	}
        	curr = curr.next;
        }
        
        if(l1 == null) {
        	curr.next = l2;
        } else {
        	curr.next = l1;
        }
        return head.next;
    }
}