JZ16-合并两个排序的链表
合并两个排序的链表
https://www.nowcoder.com/practice/d8b6b4358f774294a89de2a6ac4d9337?tpId=13&tags=&title=&diffculty=0&judgeStatus=0&rp=1&tab=answerKey
/**
* 迭代
*/
public static ListNode mergeTwoLists(ListNode list1, ListNode list2) {
if (list1 == null) {
if (list2 == null) {
return null;
}
return list2;
}
if (list2 == null) {
return list1;
}
ListNode dummy = new ListNode(-1);
ListNode tempEnd = dummy;
while (list1 != null && list2 != null) {
if (list1.val <= list2.val) {
tempEnd.next = list1;
list1 = list1.next; //看list1的下一位和list2的该位谁大,继续while
} else {
tempEnd.next = list2;
list2 = list2.next; //同理
}
tempEnd = tempEnd.next; //一个循环,插入一位,end后移一位
}
if (list1 != null) { //如果list1的数量较多,则直接接在后面。此时剩余的首位一点比原本的末尾要大
tempEnd.next = list1;
}
if (list2 != null) { //同理
tempEnd.next = list2;
}
return dummy.next;
}
/**
* 递归 把比当前大的数中的最小的赋给当前的下一位 不用细想
*/
public static ListNode mergeTwoLists2(ListNode list1, ListNode list2) {
if (list1 == null) {
if (list2 == null) {
return null;
}
return list2;
}
if (list2 == null) {
return list1;
}
if (list1.val <= list2.val) {
list1.next = mergeTwoLists2(list1.next, list2); //如果list1小于list2,则让list1的下一位继续比。然后将更小的赋给list1.next
return list1;
} else {
list2.next = mergeTwoLists2(list1, list2.next);
return list2;
}
}
三奇智元机器人科技有限公司公司福利 70人发布
