增加一個pre 和next 節點進行鏈表内部的翻轉
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def reverseKGroup(self, head, k):
"""
:type head: ListNode
:type k: int
:rtype: ListNode
"""
def reverselist(pre,next):
last=pre.next
cur=last.next
while cur!=next:
last.next=cur.next
cur.next=pre.next
pre.next=cur
cur=last.next
return last
if head==None or k==1:
return head
pre=ListNode(-1)
ret=pre
pre.next=head
cur=head
count=0
while cur!=None:
count=count+1
if count % k ==0:
#reverse pre list
pre=reverselist(pre,cur.next)
cur=pre.next
else:
cur=cur.next
return ret.next