Description
Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.
k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is.
Note:
Only constant extra memory is allowed.
You may not alter the values in the list’s nodes, only nodes itself may be changed.
Example
Given this linked list: 1->2->3->4->5
For k = 2, you should return: 2->1->4->3->5
For k = 3, you should return: 3->2->1->4->5
Submissions
这道题的解题思路参考https://leetcode-cn.com/problems/reverse-nodes-in-k-group/solution/tu-jie-kge-yi-zu-fan-zhuan-lian-biao-by-user7208t/
图解:
主要分为几步:
1.将链表分为已翻转,待翻转和未翻转三个部分
2.初始化一个虚拟节点out,待翻转区的前驱节点pre和后继节点end初始化等于out节点
3.循环找到待翻转区的范围,每循环一次,end向后走一步,循环k次后end则位于待翻转区的末尾节点,初始化start=pre.next,得到了待翻转区的范围[start, end]
4.记录end的后一个节点next=end.next,以便翻转后将整个链表的三个部分进行连接,然后将end.next置为None
5.对待翻转区进行翻转,并令pre指向翻转后的新节点,此时start为翻转后的尾节点,将start指向next,使得与下一个部分进行连接
6.更新pre和end,pre=end=start,然后进入下一次循环,直到end为None结束
最后需要注意的是,如果翻转部分长度不足 k 时,则不翻转
实现代码如下:
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def reverseKGroup(self, head: ListNode, k: int) -> ListNode:
out = ListNode(-1)
pre, end, pre.next, end.next = out, out, head, head
while end:
for i in range(k):
if end is None:
break
end = end.next
if end is None:
break
start, _next, end.next = pre.next, end.next, None
pre.next, start.next = self.reverse(start), _next
end = pre = start
return out.next
def reverse(self, head):
pre, cur = None, head
while cur:
cur.next, pre, cur = pre, cur, cur.next
return pre