LeetCode:Merge Two Sorted Lists - 拼接两个有序链表

1、题目名称

Merge Two Sorted Lists(按升序拼接两个有序链表)

2、题目地址

https://leetcode.com/problems/merge-two-sorted-lists/

3、题目内容

英文: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.

中文:给定两个已经排好序(升序)的链表,将它们拼接成一个新的有序(升序)链表

4、解题方法

本题的解决方法比较比较简单明了,Java代码如下:

/**
 * @功能说明:LeetCode 88 - Merge Two Sorted Lists
 * @开发人员:Tsybius2014
 * @开发时间:2015年11月16日
 */
public class Solution {
    
    /**
     * 按升序拼接两个有序链表
     * @param l1 链表1
     * @param l2 链表2
     * @return
     */
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        ListNode start = new ListNode(0);
        ListNode result = start;
        while (l1 != null || l2 != null) {
            if (l1 == null || (l1 != null && l2 != null && l1.val >= l2.val)) {
                result.next = new ListNode(l2.val);
                result = result.next;
                l2 = l2.next;
            } else {
                result.next = new ListNode(l1.val);
                result = result.next;
                l1 = l1.next;
            } 
        }
        return start.next; 
    }
}

END

转载于:https://my.oschina.net/Tsybius2014/blog/531146

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值