25. k个一组翻转链表
给出一个链表,每k 个节点一组进行翻转,并返回翻转后的链表。
k 是一个正整数,它的值小于或等于链表的长度。如果节点总数不是k 的整数倍,那么将最后剩余节点保持原有顺序。
示例 :
给定这个链表:1->2->3->4->5
当k = 2 时,应当返回: 2->1->4->3->5
当k = 3 时,应当返回: 3->2->1->4->5
说明 :
你的算法只能使用常数的额外空间。
你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def reverseKGroup(self, head, k):
"""
:type head: ListNode
:type k: int
:rtype: ListNode
"""
if head == None or head.next == None:
return head
newTail = None
begin = None
isFirst = True
isOver = False
isEnd = False
while not isOver and head.next!=None:
lenght = k
headI = head
headJ = headI
while lenght>1 and headI.next!=None :
headI = headI.next
lenght-=1
if lenght>1 or headI.next==None :
isOver = True
if lenght>1:
isEnd = True
head = headI.next
headI.next=None
if not isEnd:
data = self.fanzhuan(headJ)
else:
self.newHead = headJ
data = headI
if isFirst:
newTail = data
begin = self.newHead
isFirst = False
else:
newTail.next = self.newHead
newTail = data
if not isOver and head.val!=None:
newTail.next = head
return begin
newHead = None
def fanzhuan(self, head):
if head.next==None:
self.newHead = head
return head
else:
data = self.fanzhuan(head.next)
head.next = None
data.next = head
return head
作者:不爱去冒险的少年y
链接:https://www.jianshu.com/p/c9c54fb8898c