You are given a Linked List and a function declaration as node* KReverse(node* head, int k);
KReverse is a function that reverses the nodes of a Linked List k at a time and then returns the modified Linked List.
For Example
Linked List : 1->2->3->4->5->6->7->8->9->10->11
For k = 2
Return Value: 2->1->4->3->6->5->8->7->10->9->11
For k = 3
Return value: 3->2->1->6->5->4->9->8->7->10->11
Write a solid secure definition for the function KReverse.
node* Kreverse(node* head, int len, int k)
{
node* tail=head;
node* nextHead=head;
for(int i=0;i < k;i++)
nextHead=nextHead->next;
head=reverse(head,k);
for(int idx=k;idx < len;idx=i+k)
{
node* oldNextHead=nextHead;
for(int i=0;i < k;i++)
{
if(nextHead->next)
nextHead=nextHead->next;
}
tail->next=reverse(oldNextHead,k);
for(int i=0;i < k;i++)
{
if(tail->next)
tail=tail->next;
}
}
return head;
}
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment