Merge _Two_Sorted_Lists

The main purpose of this article is to complete the merging of two sorted lists.

"""
Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.
"""
import numpy as np

# Definition for singly-linked list.
class ListNode(object):
    def __init__(self, x):
        self.val = x
        self.next = None

"""单链表"""
class SingleLinkList(object):
    def __init__(self):
        self.__head = None
    """判断链表是否为空"""
    def is_empty(self):
            return self.__head == None
    """链表长度"""
    def length(self):
        # cur初始时指向头节点
        cur = self.__head
        count = 0
        # 尾节点指向None,当未到达尾部时
        while cur != None:
            count += 1
            # 将cur后移一个节点
            cur = cur.next
        return count
    """遍历链表"""
    def travel(self):
        cur = self.__head
        while cur != None:
            print(cur.val, end=" ")
            cur = cur.next
        print("")

    """尾部添加元素"""
    def append(self, val):
        node = ListNode(val)
    # 先判断链表是否为空,若是空链表,则将_head指向新节点
        if self.is_empty():
            self.__head = node
    # 若不为空,则找到尾部,将尾节点的next指向新节点
        else:
            cur = self.__head
            while cur.next != None:
                cur = cur.next
            cur.next = node

class Solution(object):

    def mergeTwoLists(L1,L2):
        """
        :type L1: ListNode
        :type L2: ListNode
        :rtype: ListNode
        """
        head = cur = ListNode(0)

        while L1 and L2:
            if L1.val > L2.val:
                cur.next = L2
                L2 = L2.next
            else:
                cur.next = L1
                L1 = L1.next
            cur = cur.next
        """or 返回第一个为真的值"""
        cur.next = L1 or L2
        return head.next

if __name__=="__main__":
    array1 = sorted(np.random.random_integers(1,15,5))
    array2 = sorted(np.random.random_integers(1,10,5))

    print('array1'+str(array1))
    print('array2'+str(array2))

    L1= SingleLinkList()
    L2= SingleLinkList()

    for each in array1:
        L1.append(each)

    for each in array2:
        L2.append(each)


    sol = Solution
    # print(L1._SingleLinkList__head.val)
    # print(L2._SingleLinkList__head.val)
    L = sol.mergeTwoLists(L1._SingleLinkList__head, L2._SingleLinkList__head)


    L3 = SingleLinkList()
    L3._SingleLinkList__head = L
    L3.travel()

The result of the operation is

                                                         

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值