这个解法主要问题在于递归+翻转
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
class Solution {
public:
/**
*
* @param head ListNode类
* @param k int整型
* @return ListNode类
*/
ListNode* reverseKGroup(ListNode* head, int k) {
// write code here
ListNode* tail = head;
for(int i = 0 ; i < k ; i++){
if(tail == NULL) return head;
tail = tail->next;
}
ListNode* pre = NULL;
ListNode* now = head;
while(now != tail){ //@1
ListNode* temp = now -> next; //@2
now->next = pre; //@3
pre = now; //@4
now = temp; //@5
}
head->next = reverseKGroup(tail, k); //@6
return pre;
}
};@1循环遍历tail之前的结点
@2将当前节点的下一个节点赋给临时节点
@3将当前节点的next指针指向前驱节点
@4将指针位移,将pre节点向前移动,将当前节点作为前驱节点
@5将指针唯一,将下一个节点作为当前节点
@6将每k段头节点指向下一k段,递归

京公网安备 11010502036488号