美文网首页
LinkedList:合并2个有序单链表

LinkedList:合并2个有序单链表

作者: 敲一手烂代码 | 来源:发表于2016-05-18 13:30 被阅读0次
    public Node mergeTwoLists(Node l1, Node l2) {
            if (l1==null ||l2==null) {
                return l1!=null?l1:l2;
            }
            Node head = null;
            if (l1.value<l2.value) {
                head = l1;
                l1 = l1.next;
            } else {
                head = l2;
                l2 = l2.next;
            }
            Node last = head;
            while (l1!=null&&l2!=null) {
                if (l1.value<l2.value) {
                    last.next = l1;
                    l1 = l1.next;
                } else {
                    last.next = l2;
                    l2 = l2.next;
                }
                last = last.next;
            }
            last.next = l1!=null?l1:l2;
            
            return head;
        }
    

    相关文章

      网友评论

          本文标题:LinkedList:合并2个有序单链表

          本文链接:https://www.haomeiwen.com/subject/thrwrttx.html