码迷,mamicode.com
首页 > 编程语言 > 详细

LeetCode算法题python解法:25. Reverse Nodes in k-Group

时间:2018-10-09 13:57:54      阅读:264      评论:0      收藏:0      [点我收藏+]

标签:node   class   positive   color   leetcode   ant   for   values   list   

Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.

k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is.

Example:

Given this linked list: 1->2->3->4->5

For k = 2, you should return: 2->1->4->3->5

For k = 3, you should return: 3->2->1->4->5

Note:

  • Only constant extra memory is allowed.
  • You may not alter the values in the list‘s nodes, only nodes itself may be changed.

题意大概是给定链表和一个参数K,每K个节点反转一次,剩下的节点不够K个则不反转。

这个题目对时间复杂度要求比较高,遍历到列表中通过reverse反转肯定是超时的,只能在链表上直接操作反转。

代码如下:

class Solution:
    def reverseKGroup(self, head, k):
        if head==None:
            return head
        out=[]
        while True:              #遍历链表,将链表放到一个list中,方便后续反转指向的操作
            out.append(head)
            if head.next==None:
                break
            head=head.next
        if k>len(out):
            return out[0]
        st=0
        end=k
        while True:
            for i in range(st+1,end):    #将每K个范围内的节点指向反转
                out[i].next=out[i-1]  
                
            if end+k<=len(out):          #判断K范围内最后一节点的指向,如果还存在下一个K则指向下个K的最后一个值
                out[st].next=out[end+k-1]
            elif st+k>=len(out):          #如果没有下个K则指向None
                out[st].next=None
            elif st+k<len(out)<end+k:     #如果剩下的数不够凑齐一个K,则指向剩下列表的第一个数
                out[st].next=out[end]
            st+=k
            end+=k  
            if len(out) < end:
                break
                
        if len(out)<2:
            return out[0]
        return out[k-1]

 

LeetCode算法题python解法:25. Reverse Nodes in k-Group

标签:node   class   positive   color   leetcode   ant   for   values   list   

原文地址:https://www.cnblogs.com/slarker/p/9759821.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!