做链表相关的题的工具类和方法:
ListNode
是链表的一个节点
array_to_list
:把一个array转化为链表
print_list
:打印一个链表
# -*- coding:utf-8 -*-
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def array_to_list(array: list) -> ListNode:
"""
transform an array to linked list
:param array:
:return: the head of the linked list.
"""
if len(array) == 0:
return None
cur = dummy = ListNode(None)
for i in range(len(array)):
cur.next = ListNode(array[i])
cur = cur.next
return dummy.next
def print_list(head: ListNode) -> None:
"""
print a linked list
:param head:
:return:
"""
if not head:
return
ret = ''
while head:
if not ret:
ret = str(head.val)
else:
ret = ret + '->' + str(head.val)
head = head.next
print(ret + '->None')
def mergeTwoLists(l1: ListNode, l2: ListNode) -> ListNode:
"""
循环的方法:
用了四个指针,一个是dummy,用来标记新list的开头的,cur是新list的指针,
l1, l2 分别是两个List是头指针;
cur指针与l1,l2指针是会移动的。
:param l1:
:param l2:
:return:
"""
dummy = cur = ListNode(None)
while l1 and l2: # l1,l2都不能为None,如果有一个为None跳出while
if l1.val < l2.val:
cur.next = l1
l1 = l1.next
else:
cur.next = l2
l2 = l2.next
cur = cur.next
cur.next = l1 or l2 # l1 and l2 which one is not None, the one is result
return dummy.next
def mergeTwoLists2(l1: ListNode, l2: ListNode) -> ListNode:
"""
递归的方法
:param l1:
:param l2:
:return:
"""
if not l1 or not l2:
return l1 or l2
if l1.val < l2.val:
l1.next = mergeTwoLists2(l1.next, l2)
return l1
else:
l2.next = mergeTwoLists2(l1, l2.next)
return l2