Leetcode Python-- 21 Merge Two Sorted Lists--数据结构基础---linked list

由于本人跨专业,数据结构基础较为薄弱,写这道题的时候参考了discussion区的答案,把答案读明白了,做了标注,现在这儿简单记录一下,这道题主要是要了解一下链表的基本机构以及指向是通过node1.next=node2这种赋值语句来做的,所谓排序就是在2个list当中找一个升序的指向,最后返回的是p1所以要在最后对p1先为空的情况进行判断。有空系统写一下python链表的相关知识以及常见习题类型和复杂度分析。

21. Merge Two Sorted Lists

Easy

1960271FavoriteShare

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.

Example:

Input: 1->2->4, 1->3->4
Output: 1->1->2->3->4->4

 

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

class Solution(object):
    def mergeTwoLists(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        """
        if not l1:#l1 not exists
            return l2
        if not l2:#l2 not exists
            return l1
        if l1.val>=l2.val:
            l1,l2=l2,l1
        
        p1=l1
        p2=l2
        head=l1
        while p1.next and p2:#不进入循环:只要p1.next和p2有一个是null
            if p1.next.val<=p2.val:
                p1=p1.next
                continue#p1.next<= p2,skip,next
            p1Next=p1.next
            p2Next=p2.next
            p1.next=p2#箭头顺序改变
            p2.next=p1Next
            
            p1,p2=p2,p2Next
        if p2:#假如p1先走完的话,把p2加进去,但如果p2先走完的话无所谓,因为要把p2放进p1里,所以只看p2空的时候
            p1.next=p2
        return l1

Success

Details 

Runtime: 36 ms, faster than 23.12% of Python online submissions for Merge Two Sorted Lists.

Memory Usage: 10.8 MB, less than 56.08% of Python online submissions for Merge Two Sorted Lists.

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值