首页 > 其他分享 >Leetcode刷题第十六天-链表

Leetcode刷题第十六天-链表

时间:2024-03-04 16:33:26浏览次数:17  
标签:head ListNode cur val self next 链表 Leetcode 刷题

24:两两交换链表中的节点

链接:24. 两两交换链表中的节点 - 力扣(LeetCode)

虚拟头节点

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]:
        if not head or not head.next:   return head
        dummpy=ListNode(next=head)
        left,cur=dummpy,head
        while cur and cur.next:
            right=cur.next
            tmp=right.next
            left.next=right
            right.next=cur
            cur.next=tmp
            left=cur
            cur=cur.next
        return dummpy.next
            
swapPairs

19:删除链表的倒数第n个节点

链接:19. 删除链表的倒数第 N 个结点 - 力扣(LeetCode)

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:
        if not head:    return head
        dummpy=ListNode(next=head)
        cur=dummpy.next
        lens=0
        while cur:
            cur=cur.next
            lens+=1
        cur=dummpy
        for i in range(lens-n):  cur=cur.next
        if(cur.next):    cur.next=cur.next.next
        return dummpy.next
removeNthFromEnd

链表相交

链接:面试题 02.07. 链表相交 - 力扣(LeetCode)

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

class Solution:
    def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode:
        lenA,lenB=self.get_len(headA),self.get_len(headB)
        if(lenA>lenB):
            for i in range(lenA-lenB):  headA=headA.next
        else:
            for i in range(lenB-lenA):  headB=headB.next
        while headA:
            if(headA==headB):   return headA
            headA=headA.next
            headB=headB.next
        return None
    def get_len(self,head):
        lens=0
        while head:
            lens+=1
            head=head.next
        return lens
        
getIntersectionNode

142:环形链表II

链接:142. 环形链表 II - 力扣(LeetCode)

快指针一次走两步,慢指针一次走一步,快=慢,有环:慢指针从头开始走,快指针一次走一步,快=慢,环入口

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

class Solution:
    def detectCycle(self, head: Optional[ListNode]) -> Optional[ListNode]:
        if(not head):   return head
        fast,slow=head,head
        while fast and fast.next:
            fast=fast.next.next
            slow=slow.next
            if fast==slow:
                slow=head
                while slow!=fast:
                    slow=slow.next
                    fast=fast.next
                return slow
        return None
detectCycle

2:两数相加

链接:2. 两数相加 - 力扣(LeetCode)

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
        cur1,cur2=l1,l2
        head=ListNode()
        re,cur=head,head
        num=0
        while cur1 or cur2:
            if(cur1):   
                c1=cur1.val
                cur1=cur1.next
            else:   c1=0
            if(cur2):   
                c2=cur2.val
                cur2=cur2.next
            else:   c2=0
            sums=c1+c2+num
            if(sums<10):
                re.val=sums
                num=0
            else:
                num=1   
                re.val=sums%10
            if(cur1 or cur2):
                re.next=ListNode()
                re=re.next
        if(num==1):
            re.next=ListNode(1)
        return head
addTwoNumbers

21:合并两个有序链表

链接:21. 合并两个有序链表 - 力扣(LeetCode)

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:
        if(not list1):  return list2
        if(not list2):  return list1
        if(list1.val<list2.val):    
            re=ListNode(list1.val)
            list1=list1.next
        else:   
            re=ListNode(list2.val)
            list2=list2.next
        cur=re
        while list1 or list2:
            if(not list1):
                cur.next=list2
                break
            if(not list2):
                cur.next=list1
                break
            if(list1.val<list2.val):
                val=list1.val
                list1=list1.next
            else:
                val=list2.val
                list2=list2.next
            cur.next=ListNode(val)
            cur=cur.next
        return re
mergeTwoLists

23:合并k个升序链表

链接:23. 合并 K 个升序链表 - 力扣(LeetCode)

链表转list,list转链表

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def mergeKLists(self, lists: List[Optional[ListNode]]) -> Optional[ListNode]:
        re=[]
        for node in lists:
            while node:
                re.append(node.val)
                node=node.next
        re.sort()
        if(len(re)==0): return None
        head=ListNode(re[0])
        cur=head
        for i in range(1,len(re)):
            cur.next=ListNode(re[i])
            cur=cur.next
        return head
mergeKLists

25:K个一组翻转链表

链接:25. K 个一组翻转链表 - 力扣(LeetCode)

cur记录翻转前一个位置,left翻转起点,right翻转终点

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def reverseKGroup(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:
        if(not head):   return head
        dummpy=ListNode(next=head)
        cur,left,right=dummpy,head,dummpy
        i=0
        while right:
            if(i==k):
                tmp=right.next
                right.next=None
                cur.next=self.reverseList(left)
                left.next=tmp
                right,cur=left,left
                left=left.next
                i=0
            i+=1
            right=right.next
        return dummpy.next

    def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
        pre,cur=None,head
        while cur:
            tmp=cur.next
            cur.next=pre
            pre,cur=cur,tmp
        return pre
reverseKGroup

 

标签:head,ListNode,cur,val,self,next,链表,Leetcode,刷题
From: https://www.cnblogs.com/xiaoruru/p/18052083

相关文章

  • 【2024面试刷题】一、Spring Cloud 面试题
    1、什么是SpringCloud?SpringCloud是一系列框架的有序集合。它利用SpringBoot的开发便利性巧妙地简化了分布式系统基础设施的开发,如服务发现注册、配置中心、智能路由、消息总线、负载均衡、断路器、数据监控等,都可以用SpringBoot的开发风格做到一键启动和部署。SpringClou......
  • ctfshow刷题记录-社工篇-1
    0x00题目来源:ctfshow-网络谜踪(社工类)题目描述:flag格式为ctfshow{纬度(精确到小数点后四位,不用进位),经度(精确到小数点后四位,不用进位)}例如若找到的经纬度为(11.45149,19.19810)则flag为ctfshow{11.4514,19.1981}(附件地址:https://ctfshow.lanzoui.com/iRHlmtek0ra)......
  • ctfshow刷题记录-cry方向-1
    0x00题目来源:ctfshow菜狗杯crypto方向base47题目描述:神必字符:E9CVT+HT5#X36RF4@LAU703+F$E-0N$@68LMXCVDRJJD5@MP#7MUZDTE?WWLG1S#L@+66H@59KTWYK8TW0RV神必字典:0123456789ABCDEFGHJKLMNPQRSTUVWXYZ?!@#$%^&*-+0x01第一次做这种base换表的题目,在网上查了查相关wp,感觉自......
  • 第二节:栈相关(二叉树展开为链表、逆波兰表达式、两栈实现队列结构)
    一.        二.        三.         !作       者:Yaopengfei(姚鹏飞)博客地址:http://www.cnblogs.com/yaopengfei/声     明1:如有错误,欢迎讨论,请勿谩骂^_^。声     明2:原创博客请在转载......
  • 牛客大厂真题刷题记录
    1、问题:统计在有用户互动的最近一个月(按包含当天在内的近30天算,比如10月31日的近30天为10.2~10.31之间的数据)中,每类视频的转发量和转发率(保留3位小数)。注:转发率=转发量÷播放量。结果按转发率降序排序。selecttag,sum(if_retweet)retweet_cut,round(sum(if_retweet)/coun......
  • 147. 对链表进行插入排序(中)
    目录题目题解优化题目给定单个链表的头head,使用插入排序对链表进行排序,并返回排序后链表的头。插入排序算法的步骤:插入排序是迭代的,每次只移动一个元素,直到所有元素可以形成一个有序的输出列表。每次迭代中,插入排序只从输入数据中移除一个待排序的元素,找到它在......
  • 【LeetCode】1768_交替合并字符串_C
    题目描述给你两个字符串word1和word2。请你从word1开始,通过交替添加字母来合并字符串。如果一个字符串比另一个字符串长,就将多出来的字母追加到合并后字符串的末尾。返回合并后的字符串。示例示例1:输入:word1="abc",word2="pqr"输出:"apbqcr"解释:字符串合并情......
  • 【LeetCode】383_赎金信_C
    题目描述给你两个字符串:ransomNote和magazine,判断ransomNote能不能由magazine里面的字符构成。如果可以,返回true;否则返回false。magazine中的每个字符只能在ransomNote中使用一次。示例示例1:输入:ransomNote="a",magazine="b"输出:false示例2:输入:ran......
  • leedcode 相交链表
    会超出时间限制:classSolution:defgetIntersectionNode(self,headA:ListNode,headB:ListNode)->Optional[ListNode]:cur_b=headBcur_a=headAwhilecur_b!=None:#两个相等ifcur_b==cur_a:r......
  • 代码随想录算法训练营day11 | leetcode 20. 有效的括号、1047. 删除字符串中的所有相
    目录题目链接:20.有效的括号-简单题目链接:1047.删除字符串中的所有相邻重复项-简单题目链接:150.逆波兰表达式求值-中等题目链接:20.有效的括号-简单题目描述:给定一个只包括'(',')','{','}','[',']'的字符串s,判断字符串是否有效。有效字符串需满足:左括号必须用相同类型的右......