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
Ideas: 1. reverse K elements linked list
2. combine them together
/**
* 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 || head->next == NULL) return head;
int length = 0;
ListNode
* cur = head;
while(cur)
{
length++;
cur= cur->next;
}
if(length < k)
return head;
int times = length / k,
leftNum = length % k;
// combine/reverse K linked list
ListNode
*dummy = new ListNode(0), //
*pre = dummy;
dummy->next = head;
cur = head;
while(times > 0)
{
ListNode
*p = cur,
*q = cur;
int size = k;
while(size > 1)
{
size--;
q = q->next;
}
cur = q->next;
q->next = NULL;
//reverse list from p to q
ListNode
*r = p,
*newHead = NULL;
while(r)
{
ListNode *temp = r;
r = r->next;
temp->next = newHead;
newHead = temp;
}
pre->next = newHead;
p->next = cur;
pre = p;
times--;
}
pre->next = cur;
head = dummy->next;
delete dummy;
return head;
}
private:
ListNode *reverseLinkedList(ListNode *p)
{
if(p == NULL || p->next == NULL) return p;
ListNode
*newHead = NULL;
while(p)
{
ListNode *temp = p;
p = p->next;
temp->next = newHead;
newHead = temp;
}
return newHead;
}
};