栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

25. k个一组翻转链表

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

25. k个一组翻转链表

25. k个一组翻转链表

给出一个链表,每k 个节点一组进行翻转,并返回翻转后的链表。

k 是一个正整数,它的值小于或等于链表的长度。如果节点总数不是k 的整数倍,那么将最后剩余节点保持原有顺序。

示例 :

给定这个链表:1->2->3->4->5

当k = 2 时,应当返回: 2->1->4->3->5

当k = 3 时,应当返回: 3->2->1->4->5

说明 :

你的算法只能使用常数的额外空间。

你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。

# class ListNode:

#     def __init__(self, x):

#         self.val = x

#         self.next = None

class Solution:

    def reverseKGroup(self, head, k):

        """

        :type head: ListNode

        :type k: int

        :rtype: ListNode

        """

        if head == None or head.next == None:

            return head

        newTail = None

        begin = None

        isFirst = True

        isOver = False

        isEnd = False

        while not isOver and head.next!=None:

            lenght = k

            headI = head

            headJ = headI

            while lenght>1 and headI.next!=None :

                headI = headI.next

                lenght-=1

            if lenght>1 or headI.next==None :

                isOver = True

            if lenght>1:

                isEnd = True

            head = headI.next

            headI.next=None

            if not isEnd:

                data = self.fanzhuan(headJ)

            else:

                self.newHead = headJ

                data = headI

            if isFirst:

                newTail = data

                begin = self.newHead

                isFirst = False

            else:

                newTail.next = self.newHead

                newTail = data

        if not isOver and head.val!=None:

            newTail.next = head

        return begin

    newHead = None

    def fanzhuan(self, head):

        if head.next==None:

            self.newHead = head

            return head

        else:

            data = self.fanzhuan(head.next)

            head.next = None

            data.next = head

            return head




作者:不爱去冒险的少年y
链接:https://www.jianshu.com/p/c9c54fb8898c


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/222917.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号