题目描述:
输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。
主要思想 :
public static ListNode
Merge(ListNode list1
, ListNode list2
) {
ListNode head
= null
;
if (list1
== null
&& list2
== null
)
return head
;
if (list1
.val
<= list1
.val
) {
head
= list1
;
list1
= list1
.next
;
} else {
head
= list2
;
list2
= list2
.next
;
}
ListNode P
= head
;
while (list1
!= null
&& list2
!= null
) {
if (list1
.val
<= list2
.val
) {
P
.next
= list1
;
P
= P
.next
;
list1
= list1
.next
;
} else {
P
.next
= list2
;
P
= P
.next
;
list2
= list2
.next
;
}
}
if (list1
!= null
) {
P
.next
= list1
;
}
if (list2
!= null
) {
P
.next
= list2
;
}
return head
;
}
注意点:
判断两个链表均为空时,返回null
转载请注明原文地址: https://yun.8miu.com/read-24254.html