合并有序链表 - 3

转载出处:https://blog.csdn.net/ctianju/article/details/116745448

题目

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

思路

递归不断深入,每次都返回当前的节点,
输入:
[1,3,5,8,17] ,[2,4,7,9,250],
输出:
[1 2 3 4 5 7 8 9 16 250 ]

java代码

public class MergeListNode {
    public static void main(String[] args) {
        ListNode listNode = new ListNode(1);
        ListNode listNode2 = new ListNode(3);
        ListNode listNode3 = new ListNode(5);
        ListNode listNode4 = new ListNode(8);
        ListNode listNode5 = new ListNode(16);
        listNode.next = listNode2;
        listNode2.next = listNode3;
        listNode3.next = listNode4;
        listNode4.next = listNode5;
        listNode5.next = null;

        ListNode listNode11 = new ListNode(2);
        ListNode listNode21 = new ListNode(4);
        ListNode listNode31 = new ListNode(7);
        ListNode listNode41 = new ListNode(9);
        ListNode listNode51 = new ListNode(250);

        listNode11.next = listNode21;
        listNode21.next = listNode31;
        listNode31.next = listNode41;
        listNode41.next = listNode51;
        listNode51.next = null;

        ListNode result = merge(listNode, listNode11);
        printListNode(result);

    }

    // 打印
    public static void printListNode(ListNode listNode) {
        ListNode tempNode = listNode;
        while (tempNode != null) {
            System.out.print(tempNode.val + " ");
            tempNode = tempNode.next;

        }

        System.out.println();
    }

    public static ListNode merge(ListNode l1, ListNode l2) {
        if (l1 == null) {
            return l2;
        } else if (l2 == null) {
            return l1;
        } else if (l1.val < l2.val) {
            l1.next = merge(l1.next, l2);
            return l1;
        } else {
            l2.next = merge(l1, l2.next);
            return l2;
        }

    }

}

class ListNode {
    public int val;
    ListNode next = null;

    public ListNode(int val) {
        this.val = val;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值