题意:根据k的大小进行循环移位
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
/**
* 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 == NULL) return NULL;
if(k <= 1) return head;
ListNode* tmpN = head;
for(int i = 0; i < k - 1; ++i)
{
tmpN = tmpN->next;
if(tmpN == NULL) return head;
}
ListNode* tmpN1 = reverseKGroup(tmpN->next, k);
ListNode* tmpS = NULL;
while(k--)
{
tmpS = head;
head = head->next;
tmpS->next = tmpN1;
tmpN1 = tmpS;
}
return tmpN1;
}
};