Merge Two Sorted Lists 合并两个有序链表@LeetCode

之前做过这道题,没有用递归,做的非常痛苦。我就在想这是Level2的题怎么会怎么麻烦。。

果然用了递归变得非常简洁!以后优先选择递归的解法(特别是链表和树的题目),如果不行再用迭代!


package Level2;

import Utility.ListNode;

/**
 * Merge Two Sorted Lists
 * 
 * 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.
 * 
 */
public class S21 {

	public static void main(String[] args) {
		ListNode x1 = new ListNode(1);
		ListNode x2 = new ListNode(5);
		ListNode x3 = new ListNode(8);
		x1.next = x2;
		x2.next = x3;
		ListNode y1 = new ListNode(0);

		ListNode head = mergeTwoLists(x1, y1);
		head.print();
	}

	public static ListNode mergeTwoLists(ListNode l1, ListNode l2) {
		if (l1 == null) {
			return l2;
		}
		if (l2 == null) {
			return l1;
		}

		ListNode mergedHead = null;
		if (l1.val <= l2.val) {
			mergedHead = l1;
			mergedHead.next = mergeTwoLists(l1.next, l2);
		} else {
			mergedHead = l2;
			mergedHead.next = mergeTwoLists(l1, l2.next);
		}
		return mergedHead;
	}

}



/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        ListNode mergeDM = new ListNode(0);
        ListNode dmHead = mergeDM;
        ListNode l1head = l1, l2head = l2;
        while(l1head!=null && l2head!=null){
            if(l1head.val <= l2head.val){
                dmHead.next = new ListNode(l1head.val);
                l1head = l1head.next;
            }else{
                dmHead.next = new ListNode(l2head.val);
                l2head = l2head.next;
            }
            dmHead = dmHead.next;
        }
        
        while(l1head != null){
            dmHead.next = new ListNode(l1head.val);
            l1head = l1head.next;
            dmHead = dmHead.next;
        }
        
        while(l2head != null){
            dmHead.next = new ListNode(l2head.val);
            l2head = l2head.next;
            dmHead = dmHead.next;
        }
        
        return mergeDM.next;
    }
}



你可能感兴趣的:(Leetcode,LeetCode专栏)