题目描述:
Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.
If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is.
You may not alter the values in the nodes, only nodes itself may be changed.
Only constant memory is allowed.
For 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
每次处理原始链表中剩余结点的前k个结点直到原始链表的结尾,如果原始链表中剩余结点的数目少于k个,直接把剩余结点依次加入到结果链表的尾部即可。
AC代码如下:
class Solution {
public:
ListNode* reverseKGroup(ListNode* head, int k) {
int size = 0;
ListNode* lhead = head;
ListNode* final_head = NULL;
ListNode* final_tail = NULL;
vector<ListNode*> nodes;
nodes.resize(k);
for (int i = 0; i < k; i++){
nodes[i] = NULL;
}
while (lhead){
size++;
lhead = lhead->next;
}
if (size < k) return head;
int times;
int flag = 0;
if (size % k == 0){
flag = 1;
}
else{
times = size / k;
}
int count = 0;
while (head){
if (final_head == NULL){
count++;
for (int i = 0; i < k; i++){
nodes[i] = head;
head = head->next;
}
for (int i = k - 1; i > 0; i--){
nodes[i]->next = nodes[i - 1];
}
nodes[0]->next = NULL;
final_head = nodes[k - 1];
final_tail = nodes[0];
}
else{
if (flag){
for (int i = 0; i < k; i++){
nodes[i] = head;
head = head->next;
}
for (int i = k - 1; i > 0; i--){
nodes[i]->next = nodes[i - 1];
}
nodes[0]->next = NULL;
final_tail->next = nodes[k - 1];
final_tail = nodes[0];
}
else{
if (count < times){
for (int i = 0; i < k; i++){
nodes[i] = head;
head = head->next;
}
for (int i = k - 1; i > 0; i--){
nodes[i]->next = nodes[i - 1];
}
nodes[0]->next = NULL;
final_tail->next = nodes[k - 1];
final_tail = nodes[0];
count++;
}
else{
final_tail->next = head;
return final_head;
}
}
}
}
return final_head;
}
};