首页 > 其他 > 详细

合并两个有序链表

时间:2018-10-06 10:06:20      阅读:149      评论:0      收藏:0      [点我收藏+]

将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。

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

 

合并两个有序链表

原文:https://www.cnblogs.com/otonashi/p/9746648.html

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