合并两个有序链表python3

Leetcode21题

主要实现:创建节点--创建2个单链表- 链表合并

1、创建单链表节点类

class ListNode:
    def __init__(self,val = 0, next = None):
        self.val = val
        self.next = next

2、两个有序链表创建(使用尾插法)

    l1 = [1,2,4]
    l2 = [1,3,4]
    head1 = ListNode(0)
    head2 = ListNode(0)
    cur1 = head1
    cur2 = head2
# 单链表1
    for i in range(len(l1)):
        list1 = ListNode(l1[i])
        cur1.next = list1
        cur1 = cur1.next

#单链表2
    for j in range(len(l2)):
        list2 = ListNode(l2[j])
        cur2.next = list2
        cur2 = cur2.next

3、合并这两个链表

class Solution:
    def mergeTwoLists(self,list1,list2):
        prehead = ListNode(-1)
        pre = prehead
        while list1 and list2:
            if list1.val <= list2.val:
                pre.next = list1
                list1 = list1.next
            else:
                pre.next = list2
                list2 = list2.next
            pre = pre.next
        if list1 is not None and list2 is None:
            pre.next = list1
        elif list1 is None and list2 is not None:
            pre.next = list2

        return prehead.next

4 完整程序



class ListNode:
    def __init__(self,val = 0, next = None):
        self.val = val
        self.next = next

class Solution:
    def mergeTwoLists(self,list1,list2):
        prehead = ListNode(-1)
        pre = prehead
        while list1 and list2:
            if list1.val <= list2.val:
                pre.next = list1
                list1 = list1.next
            else:
                pre.next = list2
                list2 = list2.next
            pre = pre.next
        if list1 is not None and list2 is None:
            pre.next = list1
        elif list1 is None and list2 is not None:
            pre.next = list2

        return prehead.next


if __name__ == "__main__":
    l1 = [1,2,4]
    # l1 = []
    l2 = [1,3,4]
    head1 = ListNode(0)
    head2 = ListNode(0)
    cur1 = head1
    cur2 = head2

    for i in range(len(l1)):
        list1 = ListNode(l1[i])
        cur1.next = list1
        cur1 = cur1.next


    for j in range(len(l2)):
        list2 = ListNode(l2[j])
        cur2.next = list2
        cur2 = cur2.next

    # solu = Solution()
    ans = Solution().mergeTwoLists(head1.next,head2.next)
    while ans != None:
        print(ans.val,end='')
        ans = ans.next








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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值