首页 > 其他 > 详细

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

时间:2015-11-17 01:44:16      阅读:244      评论:0      收藏:0      [点我收藏+]

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

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

原文:http://my.oschina.net/Tsybius2014/blog/531146

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!