Thursday, April 24, 2014

LeetCode:Reverse Nodes in k-Group

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

Solution:

Accumulate K nodes and reverse them. In the function "reverse," we pass curNode->next as the end condition.

ListNode *reverseKGroup(ListNode *head, int k) {
if(!head) return head;
if(k<=1) return head;
ListNode* curNode=head, *preHead=head, *curHead=head;
int num=0;
ListNode * newHead = new ListNode(0);
newHead->next = head;
preHead = newHead;
while(curNode){
num++;
if(num == 1){//for each K group, get the start node, which will become the preHead of next K group
curHead = curNode;
}
if(num == k){
ListNode* temp= curNode->next;
preHead->next = reverse(curHead, curNode->next);
preHead = curHead;//current start node becomes the preHead for the next K group
curNode = temp;
num=0;
}
else
curNode = curNode->next;
}
head = newHead->next;
delete newHead;
return head;
}
ListNode* reverse(ListNode* head, ListNode* end){
ListNode* pre=end;
ListNode* node = head;
while(node != end){
ListNode* temp= node->next;
node->next = pre;
pre = node;
node = temp;
}
return pre;//return the new head
}
view raw gistfile1.cpp hosted with ❤ by GitHub

No comments:

Post a Comment