# 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
"""
dummyHead = ListNode(0)
dummyHead.next = head
pre = dummyHead
fNode = head
kNode = self.hasKNode(fNode,k)
# self.reverseKList(pre,fNode,kNode,k)
#
#
# self.printList(dummyHead.next)
# pre = fNode
# fNode = pre.next
# kNode = self.hasKNode(fNode,k)
#
# print kNode.val
#
# self.reverseKList(pre, fNode, kNode, k)
# self.printList(dummyHead.next)
while kNode:
self.reverseKList(pre,fNode,kNode,k)
pre = fNode
fNode = pre.next
kNode = self.hasKNode(fNode,k)
return dummyHead.next
def hasKNode(self,head,k):
count = 1
cur = head
while cur and count < k:
cur = cur.next
count += 1
if cur:
return cur
else :
return None
def reverseKList(self,pre,fNode,Knode,k):
curNode = fNode.next
nextKnode = Knode.next
fNode.next = nextKnode
# while curNode != nextKnode:
# curNode.next = pre.next
# pre.next = curNode
# curNode = curNode.next
for i in range(k-1):
nextCur = curNode.next
curNode.next = pre.next
pre.next = curNode
curNode = nextCur
def creatList(self,l):
dummyHead = ListNode(0)
pre = dummyHead
for i in l:
pre.next = ListNode(i)
pre = pre.next
return dummyHead.next
def printList(self,head):
cur = head
while cur:
print cur.val
cur = cur.next
l1 = [1,2,3,4,5]
s = Solution()
head = s.creatList(l1)
s.printList(head)
head = s.reverseKGroup(head,3)
#
s.printList(head)