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.
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 {
private:
void reverse2(ListNode* &start, ListNode* &end) {
if (start == NULL || start->next == NULL || start == end)
return;
ListNode* preNode = start;
ListNode* curNode = start->next;
ListNode* nextNode;
ListNode* retLast = start;
while (curNode != end)
{
nextNode = curNode->next;
curNode->next = preNode;
preNode = curNode;
curNode = nextNode;
}
curNode->next = preNode;
start = curNode;
end = retLast;
}
public:
/**
* @param head a ListNode
* @param k an integer
* @return a ListNode
*/
ListNode *reverseKGroup(ListNode *head, int k) {
ListNode newHead(0);
ListNode *preGroupLast = &newHead;
ListNode *curNode = head;
ListNode* startNode;
ListNode* endNode;
while (curNode)
{
int count=0;
startNode = curNode;
while (curNode && count != k-1)
{
curNode = curNode->next;
count++;
}
if (count == k-1 && curNode)
{
endNode = curNode;
curNode = curNode->next; // point to the first position of next group
reverse2(startNode, endNode);
preGroupLast->next = startNode;
preGroupLast = endNode;
endNode->next = NULL; // 这一步很关键这一步防止 1->2->3->4->null k = 4的情况,反转以后 4->3->2->1->null, 1要指向NULL
count = 0;
}
else
{
preGroupLast->next = startNode; //break from the count++ looping;
}
}
return newHead.next;
// Write your code here
/*
ListNode newHead(0);
ListNode* curNode = head;
ListNode* preFirst = &newHead;
ListNode *preNode;
ListNode *nextNode;
ListNode* curFirst = NULL;
while (curNode && curNode->next)
{
int loop = 0;
preNode = curNode;
curNode = curNode->next;
while (curNode && loop<k-1)
{
if (loop == 0)
curFirst = preNode;
nextNode = curNode->next;
curNode->next = preNode;
preNode = curNode;
curNode = nextNode;
loop++;
}
preFirst->next = preNode;
preFirst = curFirst;
}
preFirst->next = curNode;
return newHead.next;
*/
}
};