题目描述:输入两个递增排序的链表,合并这两个链表并使新链表中的节点仍然是递增排序的。
问题分析: 当合并两个有序的列表的时候,首先想到的应该是归并排序,同时要考虑代码的健壮性的问题
1 当链表1为空的时候,链表2不为空,那么合并后的链表为2链表;
2 当链表2为空的时候,链表1不为空,那么合并后的链表为1链表;
3 当链表1和链表2都为空的时候,那么合并后的链表为空。、
采用归并排序思想代码如下
/**
* 输入两个单调递增的链表,输出两个链表合成后的链表,
* 当然我们需要合成后的链表满足单调不减规则。
* key:
* 类似于归并排序
* 非递归方式
* @param list1
* @param list2
* @return
*/
public ListNode Merge(ListNode list1,ListNode list2) {
if(list1 == null && list2 == null) // 两个链表为空
return null;
else if(list1 == null) // 链表1为空,链表2不为空时,合并结果为链表2;
return list2;
else if(list2 == null) // 链表1不为空,链表2为空时,合并结果为链表1;
return list1;
ListNode pHead;
ListNode pNode;
// 确定合并链表的头结点
if(list1.val < list2.val) {
pHead = list1;
list1 = list1.next;
} else {
pHead = list2;
list2 = list2.next;
}
// 归并合并
pNode = pHead;
while(list1 != null && list2 != null) {
if(list1.val < list2.val) {
pNode.next = list1;
list1 = list1.next;
pNode = pNode.next;
} else {
pNode.next = list2;
list2 = list2.next;
pNode = pNode.next;
}
}
// 确定尾节点
if(list1 == null)
pNode.next = list2;
if(list2 == null)
pNode.next = list1;
return pHead;
}
递归的代码如下:
public ListNode MergeRecursive(ListNode list1,ListNode list2) {
if(list1 == null && list2 == null)
return null;
else if(list1 == null)
return list2;
else if(list2 == null)
return list1;
ListNode pMergeHead = null;
if(list1.val <= list2.val) {
pMergeHead = list1;
pMergeHead.next = MergeRecursive(list1.next, list2);
} else {
pMergeHead = list2;
pMergeHead.next = MergeRecursive(list1, list2.next);
}
return pMergeHead;
}
1
参考资料: 剑指offer 何海峰 电子工业出版社