思想:;链表1的头结点的值小于链表2的头结点的值,因此链表1的头结点是合并后的链表的头结点。在剩余的结点中,链表2的头结点的值小于链表1的头结点的值,因此链表2的头结点是剩余结点的头结点,把这个结点和之前合并好的链表的尾结点链接起来。
注意事项:在非递归版本中,注意在两个链表b比较后,有些链表可能还有剩余,因此还需要继续添加在合并后的链表中。
java代码:
/* public class ListNode { int val; ListNode next = null; ListNode(int val) { this.val = val; } }*/ public class Solution { public ListNode Merge(ListNode list1,ListNode list2) { ListNode mergeList= null; if(list1==null){ return list2; } if(list2==null){ return list1; } if(list1.val<list2.val){ mergeList=list1; mergeList.next=Merge(list1.next,list2); } else{ mergeList=list2; mergeList.next=Merge(list1,list2.next); } return mergeList; } }
python代码:
class Solution: # 返回合并后列表 def Merge(self, pHead1, pHead2): if pHead1==None: return pHead2 if pHead2==None: return pHead1 if pHead2==None and pHead1==None: return None mergeList=ListNode(100) p=mergeList while pHead1 and pHead2: if pHead1.val<pHead2.val: mergeList.next=pHead1 pHead1=pHead1.next else: mergeList.next=pHead2 pHead2=pHead2.next mergeList=mergeList.next mergeList.next=pHead1 or pHead2 return p.next