输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。
其实思路跟归并排序差不多,注意边界值
1.两个List都为空,则返回空
2.其中一个List为空,则返回不为空的List
循环解法:
public static ListNode merge(ListNode list1,ListNode list2) { if(list1==null||list2==null) { if(list1==null) { return list2; } else if (list2==null) { return list1; } else { return null; } } ListNode leftCurrent=list1; ListNode rightCurrent=list2; ListNode prehead=new ListNode(0); ListNode leftPrevious=null; ListNode rightPrevious=null; //先决定谁是头指针 if(leftCurrent.val>rightCurrent.val) { prehead.next=rightCurrent; rightPrevious=rightCurrent; rightCurrent=rightCurrent.next; } else { prehead.next=leftCurrent; leftPrevious=leftCurrent; leftCurrent=leftCurrent.next; } //进行合并,当两者都没有到达最后一个点时 while(rightCurrent!=null&&leftCurrent!=null) { if(leftCurrent.val>rightCurrent.val) { leftPrevious.next=rightCurrent; rightPrevious=rightCurrent; rightCurrent=rightCurrent.next; } else { rightPrevious.next=leftCurrent; leftPrevious=leftCurrent; leftCurrent=leftCurrent.next; } } //若右边链表不为空 if(rightCurrent!=null) { leftPrevious.next=rightCurrent; } //若左边链表不为空 if(leftCurrent!=null) { rightPrevious.next=leftCurrent; } return prehead.next; }
递归解法:
public static ListNode merge(ListNode list1,ListNode list2) { if(list1==null||list2==null) { if(list1==null) { return list2; } else if (list2==null) { return list1; } else { return null; } } if(list1.val>list2.val) { list2.next=merge(list1,list2.next); return list2; } else { list1.next=merge(list1.next,list2); return list1; } }