Leetcode 25:k个一组翻转链表（最详细解决方案！！！）

k 是一个正整数，它的值小于或等于链表的长度。如果节点总数不是 k 的整数倍，那么将最后剩余节点保持原有顺序。

k = 2 时，应当返回: 2->1->4->3->5

k = 3 时，应当返回: 3->2->1->4->5

• 你的算法只能使用常数的额外空间。
• 你不能只是单纯的改变节点内部的值，而是需要实际的进行节点交换。

pre                 lat
h -> 1 -> 2 -> 3 -> 4 -> 5
k = 3

pre  lpre cur       lat
h -> 1 -> 2 -> 3 -> 4 -> 5
k = 3

cur!=lat的时候我们要做的操作就是lpre.next=cur.nextcur.next=pre.nextpre.next=curcur=lpre.next

pre  lpre      cur  lat
-----------
|         |
h    1 <- 2    3 -> 4 -> 5
|         |
-----------

def _reverseGroup(self, pre, lat):
lpre = pre.next
cur = lpre.next
while cur != lat:
lpre.next = cur.next
cur.next = pre.next
pre.next = cur
cur = lpre.next

return lpre

while cur != None:
if t % k == 0:
pre = self._reverseGroup(pre, cur.next)
cur = pre.next
else:
cur = cur.next

class Solution:
def _reverseGroup(self, pre, lat):
lpre = pre.next
cur = lpre.next
while cur != lat:
lpre.next = cur.next
cur.next = pre.next
pre.next = cur
cur = lpre.next

return lpre

"""
:type k: int
:rtype: ListNode
"""
h = ListNode(-1)
pre = h

t = 1
while cur != None:
if t % k == 0:
pre = self._reverseGroup(pre, cur.next)
cur = pre.next
else:
cur = cur.next
t += 1

return h.next

• 先遍历一遍链表，统计链表长度，然后每k个链表做反转操作。
• 遍历链表的过程中，每k个链表做反转操作
class Solution:
"""
:type k: int
:rtype: ListNode
"""
h = ListNode(-1)
pre = h

while cur != None:
t = cur
count = 1
while count < k and t != None:
t = t.next
count += 1
if count == k and t != None:
for _ in range(k - 1):
lat = cur.next
cur.next = lat.next
lat.next = pre.next
pre.next = lat

pre = cur
cur = pre.next
else:
break

return h.next

class Solution:
"""
:type k: int
:rtype: ListNode
"""
h = ListNode(-1)
pre = h

while cur != None:
t = cur
count = 1
while count < k and t != None:
t = t.next
count += 1
if count == k and t != None:
for _ in range(k - 1):
lat = cur.next
cur.next = lat.next
lat.next = pre.next
pre.next = lat

pre = cur
cur = pre.next
else:
break

return h.next

• 广告
• 抄袭
• 版权
• 政治
• 色情
• 无意义
• 其他

120