First create a dummy
virtual head node named , and point its next
pointer to the head node of the original linked list.
Then, we use three pointers pre
, cur
, nex
to perform the flip operation:
First calculate the length of the linked list, and then flip k nodes each time until there are less than k nodes left in the linked list.
During the flipping process, a loop is used to exchange two adjacent nodes until the flipping is completed.
Finally, we return the pointer of the virtual head node next
, which is the head pointer of the linked list after flipping.
#include <iostream>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
ListNode* reverseKGroup(ListNode* head, int k) {
if (head == NULL || k == 1) {
return head;
}
ListNode *dummy = new ListNode(0);
dummy->next = head;
ListNode *pre = dummy, *cur = head, *nex = NULL;
int len = 0;
while (head != NULL) {
len++;
head = head->next;
}
while (len >= k) {
cur = pre->next;
nex = cur->next;
for (int i = 1; i < k; i++) {
cur->next = nex->next;
nex->next = pre->next;
pre->next = nex;
nex = cur->next;
}
pre = cur;
len -= k;
}
return dummy->next;
}
};
int main() {
ListNode *head = new ListNode(1);
head->next = new ListNode(2);
head->next->next = new ListNode(3);
head->next->next->next = new ListNode(4);
head->next->next->next->next = new ListNode(5);
Solution solution;
ListNode *result = solution.reverseKGroup(head, 2);
while (result != NULL) {
cout << result->val << " ";
result = result->next;
}
return 0;
}