1. 本题知识点
链表
2. 题目描述
输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。
3. 解题思路
创建一个新链表,每次比较输入的两个链表,将其中值较小的结点用尾插法插入新链表,最后返回新链表。
4. 代码
public class ListNode {
int val
;
ListNode next
= null
;
ListNode(int val
) {
this.val
= val
;
}
}
public class Solution {
public static ListNode
Merge(ListNode list1
, ListNode list2
) {
ListNode head
= new ListNode(-1);
ListNode cur
= head
;
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 head
.next
;
}
}