链表汇总专题~~

只要first出马,一般都没问题。

粗心!欠缺 翻转链表有一个关键是 原来的头节点只要next是None~!!!! 不可以忘记。

K个一组翻转 == 其实直接翻转差不多

这道题失败的原因 首先没有和直接翻转联系起来; 其次 有个坑。head1 在阶段性移动之后,已经移动到了前面,必须更换成最新的head1,而不是原来的,不然就是死循环

在这里插入图片描述

class Solution(object):
    def reverseKGroup(self, head, k):
        def listnode_reverse(head, k):
            res1 = head
            res2 = head.next
            while k>1:
                res3 = res2.next
                res2.next = res1
                res1 = res2
                res2 = res3
                k -= 1
            return res1, head
        first = ListNode(None)
        head1 = first
        head1.next = head
        tmp = head1
        num = 0
        while head1:
            if num == k:
                last = head1.next
                res1, res2 = listnode_reverse(tmp.next, k)
                tmp.next = res1
                res2.next = last
                num = 0
                tmp = res2
                head1 = tmp      ###########这一步是最关键的,head1这个时候已经移动到了前面,必须更换成最新的head1,而不是原来的,不然就是死循环
            num += 1
            head1 = head1.next
        return first.next

链表翻转

def listnode_reverse(head):
    res1 = head
    res2 = head.next
    res1.next = None   ##############切记,原来的头节点的next是None~~
    while res2:
        res3 = res2.next
        res2.next = res1
        res1 = res2
        res2 = res3
    return res1

两两交换节点

在这里插入图片描述

# 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: ListNode) -> ListNode:
        first = ListNode(0)
        first.next = head
        pre = first
        head1 = head
        while head1:
            if head1.next:
                res = head1.next.next
            else:
                break
            pre.next = head1.next
            pre.next.next = head1
            head1.next = res
            pre = head1
            head1 = res
        return first.next    
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值