题目描述
将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
输入:1->2->4, 1->3->4
输出:1->1->2->3->4->4
思路
- 两根指针
pointA
和pointB
分别指向两个链表 - 如果
pointA.val >= pointB.val
,pointB
指针对后移动一位 - 如果
pointA.val < pointB.val
,pointA
指针对后移动一位
实现
public class Link1 {
public static class ListNode {
int val;
ListNode next;
ListNode() {
}
ListNode(int val) {
this.val = val;
}
ListNode(int val, ListNode next) {
this.val = val;
this.next = next;
}
}
public static ListNode mergeTwoLists(ListNode l1, ListNode l2) {
ListNode head, tail;
head = tail = new ListNode(-999);
while (l1 != null && l2 != null) {
int value_1 = l1.val;
int value_2 = l2.val;
int minVal = Math.min(value_1, value_2);
if (value_1 >= value_2) {
l2 = l2.next;
} else {
l1 = l1.next;
}
tail.next = new ListNode(minVal);
tail = tail.next;
}
tail.next = l1 == null ? l2 : l1;
return head.next;
}
public static void main(String[] args) {
ListNode node1 = new ListNode(1);
node1.next = new ListNode(2, new ListNode(4));
ListNode node2 = new ListNode(1);
node2.next = new ListNode(3, new ListNode(4));
ListNode resultNode = mergeTwoLists(node1, node2);
}
}