合并两个有序链表,并将结果作为一个新的链表返回。应该通过将前两个列表的节点拼接在一起来创建新列表。
举例:
输入: 1->2->4, 1->3->4
输出: 1->1->2->3->4->4
/*
* 21. Merge Two Sorted Lists
* https://leetcode.com/problems/merge-two-sorted-lists/
* https://www.whosneo.com/21-merge-two-sorted-lists/
*/
public class MergeTwoLists {
public static void main(String[] args) {
ListNode head1 = new ListNode(1);
head1.next = new ListNode(2);
head1.next.next = new ListNode(4);
ListNode head2 = new ListNode(1);
head2.next = new ListNode(3);
head2.next.next = new ListNode(4);
MergeTwoLists solution = new MergeTwoLists();
solution.print(head1);
solution.print(head2);
ListNode node = solution.mergeTwoLists(head1, head2);
solution.print(node);
}
private void print(ListNode node) {
for (; node != null; node = node.next) {
System.out.print(node.val);
System.out.print("->");
}
System.out.println("null");
}
private ListNode mergeTwoLists(ListNode l1, ListNode l2) {
ListNode prev = new ListNode(0);
ListNode node = prev;
while (l1 != null && l2 != null) {
if (l1.val < l2.val) {
node.next = l1;
l1 = l1.next;
} else {
node.next = l2;
l2 = l2.next;
}
node = node.next;
}
node.next = l1 != null ? l1 : l2;
return prev.next;
}
}