目录
问题
思路
版本一
版本二
答案
版本一
版本二
将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
示例 1:
输入:l1 = [1,2,4], l2 = [1,3,4] 输出:[1,1,2,3,4,4]
示例二:
输入:l1 = [], l2 = [] 输出:[]
示例 3:
输入:l1 = [], l2 = [0] 输出:[0]
新建一个节点,将原来的链表都传到新的链表当中
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;elselist2 = 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;
}