reverse node in k group
decompose the task to these 6 steps:
1) head = nexthead;
2) find nexthead;
3) reverse the list
4) prev->next = tail
5) head->next = nexthead;
6) prev = head;
code
/**
* 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 dummy(0);
ListNode* prev = &dummy;
prev->next = head;
ListNode* nexthead = head;
int looptimes = len(head)/k;
for(int i = 0; i<looptimes; i++)
{
head = nexthead;
ListNode* p = nexthead;
for(int j = 0; j<k-1; j++)
{
p = p->next;
}
nexthead = p->next;
p->next = NULL;
p = head;
prev->next = reverse(p);
head->next = nexthead;
prev = head;
}
return dummy.next;
}
int len(ListNode* head)
{
int count = 0;
while(head != NULL)
{
head = head->next;
count++;
}
//cout<<count<<endl;
return count;
}
ListNode* reverse(ListNode* head)
{
if(head == NULL)
{
return NULL;
}
ListNode* p = NULL;
while(head != NULL)
{
ListNode* next = head->next;
head->next = p;
p = head;
head = next;
}
return p;
}
};