题目:
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
思路:
该题目可以看做是Leetcode 24. Swap Nodes in Pairs的一个推广(因为如果k == 2,则退化为24题)。我自己原来写的代码又长又晦涩,看了网上优雅的解法之后觉得自己的差距有二:1)如果提前计算一下整个链表的长度,则在前面几个完整的reverse过程中不再需要做长度检查,大大简化了代码;2)在reverse的过程中,可以逐个翻转,只要连续翻转k次,即完成了一个reverse。这里再次感谢虚拟头指针带来的便利!
代码:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* reverseKGroup(ListNode* head, int k) {
if(!head || k<=1)
return head;
ListNode pre_head(0);
ListNode *p = &pre_head, *q=head, *tem;
pre_head.next = head;
int len = 0;
while(p->next) // calculate the length
p = p->next, len++;
p = &pre_head;
while(len >= k)
{
int step = 1;
q = p->next;
while(step++ < k) // reverse one group
{
tem = q->next;
q->next = tem->next;
tem->next = p->next;
p->next = tem;
}
p = q, len -= k;
}
return pre_head.next;
}
};