1.9合併兩個有序鏈表

合併兩個有序鏈表

解題思想:

分別用l1,l2遍歷兩個鏈表,若是l1.data小於l2.data,則將l1納入合併後的鏈表,l1=l1.next;反之將l2納入合併後的鏈表,l2=l2.next;若是其中一個鏈表遍歷結束,則將沒遍歷完的另外一鏈表的剩下部分納入合併後的鏈表node

代碼實現:

# -*-coding:utf-8-*- 
"""
@Author  : 圖南
@Software: PyCharm
@Time    : 2019/9/7 14:23
"""
class Node:
    def __init__(self, data=None, next=None):
        self.data = data
        self.next = next


def print_link(head):
    cur = head.next
    while cur.next != None:
        print(cur.data, end=' ')
        cur = cur.next
    print(cur.data)


def con_link(n):
    nums = list(map(int, n.split(' ')))
    head = Node()
    cur = head
    for num in nums:
        node = Node(num)
        cur.next = node
        cur = node
    return head


def mergeLink(head1, head2):
    head = Node
    cur = head
    l1 = head1.next
    l2 = head2.next
    while l1 is not None and l2 is not None:
        if l1.data < l2.data:
            cur.next = l1
            l1 = l1.next
            cur = cur.next
            cur.next = None
        else:
            cur.next = l2
            l2 = l2.next
            cur = cur.next
            cur.next = None
    if l1 is None:
        cur.next = l2
    else:
        cur.next = l1
    print_link(head)


if __name__ == '__main__':
    n1 = input("Link1:")
    n2 = input("Link2:")
    head1 = con_link(n1)
    head2 = con_link(n2)
    mergeLink(head1, head2)

運行結果:

相關文章
相關標籤/搜索