#21 Merge Two Sorted Lists
You are given the heads of two sorted linked lists
list1
andlist2
.Merge the two lists in a one sorted list. The list should be made by splicing together the nodes of the first two lists.
Return the head of the merged linked list.
解题思路:
分两种,一个是iterative的,另外一个是recursive的。后者的time 和 space complexity都是O(m+n)。前者time complexity是O(m+n),space complexity是O(1)【这里暂时不明白】。
iterative的方法是先排除两个list没有节点的情况,然后比较两个list排头的val大小,小的放入新的list中,然后继续比较后续的节点,直到其中一个list没有节点为止,就把另外一个list剩下的节点接在新list的后面。新的list操作时需要两个pointers,一个是记录整个list,head。另外一个是接最小值用的,tail。
# rule out the possibility of either list1 or list2 is None
if not list1:
if not list2:
return None
else:
return list2
else:
if not list2:
return list1
# create a new linked list
head = ListNode(0)
# attach the smallest nodes from two linked lists to the new one
while list1 and list2:
if list1.val <= list2.val:
# the first node attached to head
if not head.next:
head.next = list1