这个是关于两个链表按顺序合并的问题,首先需要判这两个链表中是否存在空链表,定义了一个空链表l,并用a指向该空链表
1,比较链表当前元素的大小,将l指向小数,并记录下小数链表的next位置
2,判断哪个链表不为空,直接加到l后面
class ListNode(object): def __init__(self, x): self.val = x self.next = None def Creatlist(n): if n <= 0: return False elif n == 1: a = ListNode(1) return a else: root = ListNode(1) tmp = root for i in range(2,n+1): tmp.next = ListNode(i) tmp = tmp.next return root l1 = Creatlist(3) l2 = Creatlist(4) # while l1: # print(l1.val) # l1 = l1.next l = ListNode(1) a = l while l1 and l2: # if l1.val <= l2.val: # l.next = ListNode(l1.val) # l = l.next # l1 = l1.next # else: # l.next = ListNode(l2.val) # l = l.next # l2 = l2.next if l1.val <= l2.val: l.next = l1 l1 = l1.next l = l.next else: l.next = l2 l2 = l2.next l = l.next if l1: l.next = l1 else: l.next = l2 a = a.next while a: print(a.val) a = a.next