合并两个有序链表 Python (第一版:.完整的代码包括输入输出在pycharm,第二版:LeetCode代码) - Go语言中文社区

合并两个有序链表 Python (第一版:.完整的代码包括输入输出在pycharm,第二版:LeetCode代码)


第一版:.完整的代码包括输入输出

#链表中结束后记得返回一个指向头结点的指针
# Definition for singly-linked list.
class ListNode:
    def __init__(self, x):
        self.val = x
        self.next = None

class LinkList:
    def __init__(self):
        self.head=None

    def initList(self, data):
        # 创建头结点
        self.head = ListNode(data[0])
        r=self.head
        p = self.head
        # 逐个为 data 内的数据创建结点, 建立链表
        for i in data[1:]:
            node = ListNode(i)
            p.next = node
            p = p.next
        return r
    def printlist(self,head):
        if head == None: return
        node = head
        while node != None:
            print(node.val,end=' ')
            node = node.next
class Solution:
    def mergeTwoLists(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        """
        head = ListNode(0)
        first = head
        while l1!=None and l2!=None:
            if l1.val <= l2.val:
                head.next = l1
                l1 = l1.next
            else:
                head.next = l2
                l2 = l2.next
            head = head.next
        if l1 != None:
            head.next = l1
        elif l2 != None:
            head.next = l2
        return first.next
if __name__ == '__main__':
    a = Solution()
    l=LinkList()
    data1 = [1, 2, 3]
    data2= [2, 4, 6]
    l1=l.initList(data1)
    l2=l.initList(data2)
    l.printlist(l1)
    print("r")
    l.printlist(l2)
    print("r")
    m=a.mergeTwoLists(l1,l2)
    l.printlist(m)

第二版:LeetCode代码
head = ListNode(0)
first = head
while l1!=None and l2!=None:
    if l1.val <= l2.val:
        head.next = l1
        l1 = l1.next
    else:
        head.next = l2
        l2 = l2.next
    head = head.next
if l1 != None:
    head.next = l1
elif l2 != None:
    head.next = l2
return first.next

版权声明:本文来源CSDN,感谢博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/ganghaodream/article/details/99682937
站方申明:本站部分内容来自社区用户分享,若涉及侵权,请联系站方删除。
  • 发表于 2020-03-08 16:26:24
  • 阅读 ( 1454 )
  • 分类:算法

0 条评论

请先 登录 后评论

官方社群

GO教程

猜你喜欢