参考算法:图解k个一组翻转链表
链表的翻转就是将当前节点的下个节点的后继节点置为当前节点。
C++代码
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
private:
void reverseList(ListNode* list){
ListNode *prep = list, *next = list->next;
prep->next = NULL;
while(next){
ListNode *tmp = next->next;
next->next = prep;
prep = next;
next = tmp;
}
return ;
}
public:
ListNode* reverseKGroup(ListNode* head, int k) {
if(k == 1){
return head;
}
ListNode* dummy = new ListNode(0);
dummy->next = head;
ListNode *prep, *next, *cur, *curhead, *curtail;
int i = 1;
prep = dummy, next = NULL, cur = head;
curhead = head, curtail = NULL;
while(cur){
i++;
cur = cur->next;
if(cur && i == k){
next = cur->next; // 后继节点确定
curtail = cur; // 当前队尾节点
curtail->next = NULL; // 当前队尾后继节点置空,方便翻转
reverseList(curhead); // 翻转链表
prep->next = curtail; // 前继节点指向k个元素中的最后一个,即翻转后的第1个
curhead->next = next; // 先前的头结点(翻转后的尾节点)指向后继节点
prep = curhead; // 翻转后的队尾节点(翻转前队首)为前继节点
next = NULL; // 后继节点置空
cur = curhead = curhead->next; // 设置新的当前队列
curtail = NULL;
i = 1;
}
}
return dummy->next;
}
};