合并两个有序链表
LeetCode题目
将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
输入:l1 = [1,2,4], l2 = [1,3,4]
输出:[1,1,2,3,4,4]
My Thought
- 一、找到最小的head节点
- 二、建立两个指针,让head从最小的head节点开始next
- 三、最后超出长度的要补齐
代码示例
JAVA
public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
ListNode head = null;
ListNode next = null;
if (null == list1 && null == list2) {
return head;
} else if (null == list1) {
return list2;
} else if (null == list2) {
return list1;
}
ListNode current1 = list1;
ListNode current2 = list2;
while (current1 != null && current2 != null) {
if (current1.val <= current2.val) {
if (head == null) {
head = current1;
next = head;
} else {
next.next = current1;
next = current1;
}
current1 = current1.next;
} else {
if (head == null) {
head = current2;
next = head;
} else {
next.next = current2;
next = current2;
}
current2 = current2.next;
}
}
next.next = current1 !=null?current1:current2;
return head;
}