一.题目
输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。
二.分析
根据题目条件,就可以联想到归并排序(Merge_Sort)
的算法,差异在于:经典的归并算法中,被排序的是数组,而,数组的容量在一开始就是被确定的,所以我们需要用o(N)
的临时空间来辅助算法的进行.而这道题目的容器是链表,故不需要这o(N)
的辅助空间;
接下来的思路就和归并排序的merge
方法类似了,此处就不做赘述了.
显然是有递归和非递归两种方案的.
三.代码
递归:
public ListNode Merge(ListNode list1,ListNode list2) {
// 容错检查
if (list1 == null && list2 == null) { // 都空
return null;
} else if (list1 == null && list2 != null) {// 其中有一个为空
return list2;
} else if (list1 != null && list2 == null) {// 其中有一个为空
return list1;
}
ListNode mergeNode=null;
if(list1.val<=list2.val){
mergeNode=list1;
mergeNode.next=Merge(list1.next,list2);
}else{
mergeNode=list1;
mergeNode.next=Merge(list1,list2.next);
}
return mergeNode;
}
非递归:
public ListNode Merge(ListNode list1,ListNode list2) {
// 容错检查
if (list1 == null && list2 == null) { // 都空
return null;
} else if (list1 == null && list2 != null) {// 其中有一个为空
return list2;
} else if (list1 != null && list2 == null) {// 其中有一个为空
return list1;
}
// 都不空
ListNode tmpNode = null;//合并链表已排序至的节点
ListNode tmpHead = null;//用于指向合并链表的头结点
while (list1 != null && list2 != null) {
if(list1.val<=list2.val){
if(tmpHead==null){
tmpHead=tmpNode=list1;
}else{
tmpNode.next=list1;
tmpNode=tmpNode.next;
}
list1=list1.next;
}else{
if(tmpHead==null){
tmpHead=tmpNode=list2;
}else{
tmpNode.next=list2;
tmpNode=tmpNode.next;
}
list2=list2.next;
}
}
if(list1!=null){
tmpNode.next=list1;
}
if(list2!=null){
tmpNode.next=list2;
}
return tmpHead;
}
四.小结
涉及到大量的指针操作,先分析清楚需要多少指针,已经指针的用处.然后在考虑边界测试,负值测试的问题.注意代码的鲁棒性.
比如说,我在开始在解的时候,并没有思考到tmpHead
指针的用处,直到最后需要返回的时候,才发现最开始的tmpNode
已经位于合并后链表的尾处了.所以需要额外的一个指针指向合并链表的头结点,用于最后返回.