LeetCode 合并两个有序链表(非递归)

# Leetcode 合并两个有序链表
# 非递归方法
# 我使用了较为笨的一种方法来接 先提取所有数到数组--->排序--->有了顺序表转换为链表就方便了
# 考虑到链表的特殊性质,我把他们一个个先实例化为一个个仅仅含有val,next都是None的链表,然后从后往前一个一个的链接上就行了

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

class Solution:
    def mergeTwoLists(self, l1, l2):
        if l1 == None and l2 == None:
            return None
        elif l1 == None and l2 != None:
            return l2
        elif l1 != None and l1 == None:
            return l1
        else:
            l1_ = []
            while l1 is not None:
                l1_.append(l1.val)
                l1 = l1.next
            l2_ = []
            while l2 is not None:
                l2_.append(l2.val)
                l2 = l2.next

            final = l1_ + l2_
            final = sorted(final)

            # list2ListNode
            each_node = []
            for ele in final:
                each_node.append(ListNode(ele))

            length = len(each_node) - 1
            i = 0
            while i != length:
                each_node[length - i - 1].next = each_node[length - i]
                i += 1

            return each_node[0]
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章