美文网首页
Day 32 使用递归合并两个有序列表(尚未完成)

Day 32 使用递归合并两个有序列表(尚未完成)

作者: 快乐的老周 | 来源:发表于2020-06-24 23:32 被阅读0次

使用递归合并两个有序列表

输入:1->2->4, 1->3->4
输出:1->1->2->3->4->4
补全下面代码:

class Node():
def init(self, val):
self.val = val
self.next = None

class SingleLinkList():
def init(self):
self.head = None

def is_empty(self):
    if self.head == None:
        return True

def length(self):
    cur = self.head
    count = 0
    while cur != None:
        cur = cur.next
        count +=1
    return count

def travel(self):
    cur = self.head
    while cur != None:
        print(cur.val, end=' ')
        cur = cur.next
    print('\n')

def append(self, item):
    node = Node(item)
    cur = self.head
    if self.is_empty():
        self.head = node
    else:
        while cur.next != None:
            cur = cur.next
        cur.next = node

def reverseList(self):
    # if self.head == None or self.head.next == None:
        # return self.head
    pre = None
    cur = self.head
    while cur != None:
        next = cur.next
        cur.next = pre
        pre = cur
        self.head = next

def merge(l1, l2):
if not l1: return l2
if not l2: return l1
if l1.val <= l2.val:
l1.next =merge(l1.next, l2)
return l1
if l2.val < l1.val:
l2.next = merge(l1.next, l2)
return l2

if name == 'main':
l1 = SingleLinkList()
l1.append(1)
l1.append(2)
l1.append(4)

l2 = SingleLinkList()
l2.append(1)
l2.append(3)
l2.append(4)

l1.travel()
print('*'*40)
l2.travel()


print('*'*40)
merge(l1, l2)
l1.travel()

相关文章

网友评论

      本文标题:Day 32 使用递归合并两个有序列表(尚未完成)

      本文链接:https://www.haomeiwen.com/subject/jmhqfktx.html