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
时间: 2024-10-13 19:46:00