mergeTwoList

来源:互联网 发布:mapreduce python编程 编辑:程序博客网 时间:2024/05/18 03:30

这个是关于两个链表按顺序合并的问题,首先需要判这两个链表中是否存在空链表,定义了一个空链表l,并用a指向该空链表

1,比较链表当前元素的大小,将l指向小数,并记录下小数链表的next位置

2,判断哪个链表不为空,直接加到l后面

class ListNode(object):    def __init__(self, x):        self.val = x        self.next = Nonedef 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 rootl1 = Creatlist(3)l2 = Creatlist(4)# while l1:#     print(l1.val)#     l1 = l1.nextl = ListNode(1)a = lwhile 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.nextif l1:    l.next = l1else:    l.next = l2a = a.nextwhile a:    print(a.val)    a = a.next

0 0
原创粉丝点击