数据结构算法操作试题(C++/Python)——k个一组翻转链表


数据结构算法操作试题(C++/Python):数据结构算法操作试题(C++/Python)——目录


1. 题目

leetcode 链接:https://leetcode-cn.com/problems/reverse-nodes-in-k-group/

在这里插入图片描述

2. 解答

2.1 K步距普通解法

python:732ms, 12.4 Mb

class Solution(object):
    def reverseKGroup(self, head, k):
        """
        :type head: ListNode
        :type k: int
        :rtype: ListNode
        """
        tmp_head = pre_head = ListNode(0)
        pre_head.next = head
        while self.judgekNode(tmp_head, k):
            i = k
            nextk_p = self.NodekNext(tmp_head, k + 1)
            while i != 1:
                self.NodekNext(tmp_head, i).next = tmp_head.next
                tmp_head.next = self.NodekNext(tmp_head, i)
                tmp_head = tmp_head.next
                i -= 1
            tmp_head = tmp_head.next
            tmp_head.next = nextk_p
        return pre_head.next
        
    def NodekNext(self, node, k):
        while k:
            node = node.next
            k -= 1
        return node
    
    def judgekNode(self, node, k):
        node = node.next
        while k:
            if not node: return False
            node = node.next
            k -= 1
        return True

2.2 递归

python: 44ms , 12.7 Mb

class Solution(object):
	def reverseKGroup(self, head, k):           
        cnt = 0
        check = head
        while  cnt < k and check != None:
            cnt += 1
            check = check.next
        
        if cnt < k:
            return head
        
        point = head
        prev = self.reverseKGroup(check, k)
        while point != check:
            tmp = point.next
            point.next = prev
            prev = point
            point = tmp
        
        return prev

其他方法看 leetcode 链接 评论区~

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值