示例 1:
输入:l1 = [1,2,4], l2 = [1,3,4]
输出:[1,1,2,3,4,4]
示例二:
8e99a69fbe029cd4e2b854e244eab143输入:128dba7a3a77be0113eb0bea6ea0a5d0l1 = [], l2 = []
8e99a69fbe029cd4e2b854e244eab143输出:128dba7a3a77be0113eb0bea6ea0a5d0[]
示例 3:
输入:l1 = [], l2 = [0]
输出:[0]
思路版本一新建一个空的链表 nlist
在两个链表(l1,l2)都不为空的情况下,比较两个链表的第一个元素的值的大小,取出最小的加入到新链表当中,然后小链表的头指针指向下一位,并且nlist的指针也指向下一位
如果两个链表还都不为空,继续循环
如果两个链表有一个为空,那么将不为空的链表拼接到nlist后边
最后返回 nlist 的next 作为新链表的头结点
版本二首先判断两个链表是否为空,为空直接返回空链表。不为空的继续向下走
判断 l1 和 l2的头结点谁更小,则将这个节点保存为头结点,后边的节点一次拼接在该节点上边。
后边思路同版本一
答案版本一新建一个节点,将原来的链表都传到新的链表当中
public listnode mergetwolists(listnode list1, listnode list2) { listnode head = new listnode(-1); listnode = head; while (list1 != null && list2 != null) { boolean b = list1.val <= list2.val; all.next = b ? list1 : list2; if (b) list1 = list1.next; else list2 = list2.next; all = all.next; } all.next = list1 != null ? list1 : list2; return head.next;}
版本二从原来的链表中选择出来一个进行整合,不适用任何新的内存
public listnode mergetwolists(listnode list1, listnode list2) { if (list1 == null || list2 == null) { return list1 == null ? list2 : list1; } listnode head = list1.val <= list2.val ? list1 : list2; if (list1.val <= list2.val) list1 = list1.next; else list2 = list2.next; listnode tmp = head; while (list1 != null && list2 != null) { boolean b = list1.val <= list2.val; tmp.next = b ? list1 : list2; if (b) list1 = list1.next; else list2 = list2.next; tmp = tmp.next; } tmp.next = list1 != null ? list1 : list2; return head;}
以上就是java有序链表怎么合并的详细内容。
