题目描述
输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。
思路分析
这题的链表版本和数组版本思路是一致。循环比较两个链表结点大小,小的就加入新的链表,并将指针向后移动。最后肯定有一个链表不为空,就把不为空的链表加在返回链表之后。
代码实现
public ListNode Merge(ListNode list1,ListNode list2) {
if (list1 == null || list2 == null) {
return list1 == null ? list2 : list1;
}
ListNode head = new ListNode(0);
head.next = null;
ListNode root = head;
while (list1 != null && list2 != null) {
if (list1.val < list2.val) {
head.next=list1;
head=head.next;
list1=list1.next;
} else {
head.next=list2;
head=head.next;
list2=list2.next;
}
}
if (list1 != null) {
head.next = list1;
}
if (list2 != null) {
head.next = list2;
}
return root.next;
}