1.9合并两个有序链表

合并两个有序链表

解题思想:

分别用l1,l2遍历两个链表,如果l1.data小于l2.data,则将l1归入合并后的链表,l1=l1.next;反之将l2归入合并后的链表,l2=l2.next;如果其中一个链表遍历结束,则将没遍历完的另一链表的剩下部分归入合并后的链表

代码实现:

# -*-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)

运行结果:

posted @ 2019-09-07 14:52  上进的小苗同学  阅读(126)  评论(0编辑  收藏  举报