#链表以k个结点为一组进行翻转(如1->2->3->4->5->6->7,k=3时,结果为3->2->1->6->5->4->7)
class Node:
def __new__(self,value=None,next=None):
self.value=value
self.next=next
def Reversekgroup(self,head,k):
if head==None or head.next==None or k<2:
return 0
cur=head #初始化cur为head
count=0 #count用于计数分组,count=k-1时,生成一个k分组
while cur.next!=None and count!=k: #通过设置cur,把原先的链表切成几段,每一段在一个递归体里面进行处理
cur=cur.next
count+=1
if count==k:
cur=self.Reversekgroup(cur,k)
while count>0:
temp=head.next
head.next=cur
cur=head
head=temp
count-=1
head=cur
return head
python链表以k个结点为一组进行翻转(如1->2->3->4->5->6->7,k=3时,结果为3->2->1->6->5->4->7)
最新推荐文章于 2024-07-12 16:16:27 发布