25. Reverse Nodes in k-Group
题目: 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
分析: 基础题考察链表的基本操作. 首先遍历一遍链表, 记录链表的节点数; 然后求出分组数. 对每一分组分别进行处理, 在处理的过程中设置两个指针, 分别指向当前节点和当前节点的下一个节点, 采用头插法逆序每一分组的节点.
code:
class Solution {
public:
ListNode* reverseKGroup(ListNode* head, int k) {
if(!head)
return NULL;
if(k == 1)
return head;
int nums = 0;
int groups = 0;
ListNode* q = NULL, *r = NULL;
for(q = head; q; q = q->next) {
nums++;
}
groups = nums / k;
r = head;
ListNode* p = new ListNode(0);
head = p;
while(groups--) {
for (int i = 0; i < k; ++i) {
q = r;
r = r->next;
q->next = p->next;
p->next = q;
}
for (int i = 0; i < k; ++i) {
p = p->next;
}
}
p->next = r;
q = head->next;
delete head;
return q;
}
};