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

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]

 

转载于:https://www.cnblogs.com/slarker/p/9759821.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值