LeetCode 21. Merge Two Sorted Lists——python(easy)——使用了链表

题目来源:

题目分析:

  题目给出两个排好序的链表,将这两个链表整合成一个新的有序的链表。
这里通过看程序可以发现定义了一个ListNode类来描述链表。并且这里构建的是单链表。需要注意的是我们需要定义一个虚表头,并且注意不要让它移动,设定一个yau=tou,然后两个表的指针一步步移动,并通过比较val的大小决定哪个插入yau.next;最后返回tou.next就可以获得正确的结果

程序代码:

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

class Solution:
    def mergeTwoLists(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        """
        if(not l1 and not l2):
            return
        tou=ListNode(0)
        yau=tou

        while (l1 and l2):
            if(l1.val<=l2.val):
                yau.next=l1
                l1=l1.next
            else:
                yau.next=l2
                l2=l2.next
            yau=yau.next
        yau.next=(l1 or l2)
        return (tou.next)
测试代码(网上当的):但是运行时什么都没有出现,不知道为什么!有大神可以解答吗?

arr1=[1,2,3]
arr2=[4,5,6]
l1=ListNode(arr1[0])
p1=l1
l2=ListNode(arr2[0])
p2=l2
for i in arr1[1:]:
    p1.next=ListNode(i)
    p1=p1.next
for i in arr2[1:]:
    p2.next=ListNode(i)
    p2=p2.next
s=Solution()
q=s.mergeTwoLists(l1,l2)




 

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