合并两个有序链表
将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
输入:l1 = [1,2,4], l2 = [1,3,4]
输出:[1,1,2,3,4,4]
package TOP21_30;
import Util.ListNode;
import java.util.ArrayList;
import java.util.List;
//合并两个有序链表
//将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
//输入:l1 = [1,2,4], l2 = [1,3,4]
//输出:[1,1,2,3,4,4]
public class Top25 {
//数组排序
public static ListNode mergeTwoLists2(ListNode list1, ListNode list2) {
List<ListNode> nodeList = new ArrayList<>();
ListNode res = new ListNode(0);
while (list1 != null) {
nodeList.add(list1);
list1 = list1.next;
}
while (list2 != null) {
nodeList.add(list2);
list2 = list2.next;
}
nodeList.sort((s1, s2) -> (s1.val - s2.val));
for (int i = 0; i < nodeList.size(); i++) {
ListNode node = nodeList.get(i);
if (i == 0) {
res.next = node;
}
if (i <= nodeList.size() - 2) {
node.next = nodeList.get(i + 1);
}
if (i == nodeList.size() - 1) {
node.next = null;
}
}
return res.next;
}
// 双指针
public static ListNode mergeTwoLists(ListNode list1, ListNode list2) {
ListNode res = new ListNode(0), cur = res;
while (list1 != null && list2 != null) {
if (list1.val < list2.val) {
cur.next = list1;
list1 = list1.next;
} else {
cur.next = list2;
list2 = list2.next;
}
cur = cur.next;
}
// 一个到头了
if (list1 == null) {
cur.next = list2;
}
if (list2 == null) {
cur.next = list1;
}
return res.next;
}
public static void main(String[] args) {
int[] num1 = {1, 5, 7, 9};
int[] num2 = {2, 3, 6, 8};
ListNode list1 = ListNode.setNodes(0, num1);
ListNode list2 = ListNode.setNodes(0, num2);
ListNode res = mergeTwoLists(list1, list2);
ListNode.printListData(res);
}
}
harryptter / LeetcodeTop100 · GitCode