列表转链表
思路:生成一个头节点,current指向该节点,再生成新节点,给该节点赋值val,更新current位置,依次类推。
class ListNode(object):
def __int__(self,val=0,next=None):
self.val = val
self.next = next
class Solution(object):
def mergeTwoLists(list1, list2):
"""
:type list1: Optional[ListNode]
:type list2: Optional[ListNode]
:rtype: Optional[ListNode]
"""
#这里ListNode需要赋val和next
#但ListNode类初始化时有初始val和next 这里是个疑问?
ListNode.val = 0
ListNode.next = None
dummy = current = ListNode()
while list1 and list2:
if list1.val < list2.val:
current.next = list1
current = list1
list1 = list1.next
else:
current.next = list2
current = list2
list2 = list2.next
if list1 and not list2:
current.next = list1
elif not list1 and list2:
current.next = list2
return dummy.next
def list2link(list):#列表转链表
current = head = ListNode()
for i in range(len(list)):
current.val= list[i]
current.next = ListNode()
current = current.next
return head
list1 = [1,2,4]
list2 = [1,3,4]
listNode1 = list2link(list1)#链表首地址
listNode2 = list2link(list2)
# print (listNode1.val)
# print (listNode1.next.val)
# print (listNode1.next.next.val)
# print (listNode2.val)
# print (listNode2.next.val)
# print (listNode2.next.next.val)
a = Solution.mergeTwoLists(listNode1, listNode2)
#print (a.val)
#打印链表 第0位置是空链首
for i in range(1,len(list1)+len(list2)):
print (a.val,end=' ')
a = a.next