题目:
输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。
public static ListNode Merge(ListNode list1, ListNode list2) {
if (list1 == null) {
return list2;
}
if (list2 == null) {
return list1;
}
if (list1 == null && list2 == null) {
return null;
}
List<ListNode> list = new ArrayList<>();
ListNode cur1 = list1;
ListNode cur2 = list2;
while (cur1 != null || cur2 != null) {
if(cur1 == null){
list.add(cur2);
cur2 = cur2.next;
continue;
}
if(cur2 == null){
list.add(cur1);
cur1 = cur1.next;
continue;
}
if (cur1.val < cur2.val) {
list.add(cur1);
cur1 = cur1.next;
continue;
}
if (cur1.val >= cur2.val) {
list.add(cur2);
cur2 = cur2.next;
continue;
}
}
for (int i = 0; i < list.size() - 1; i++) {
list.get(i).next = list.get(i + 1);
}
return list.get(0);
}
网友评论