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



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值