problem id:-http://practice.geeksforgeeks.org/problems/reverse-a-linked-list-in-groups-of-given-size/1
code:--
/*
Please note that it's Function problem i.e.
you need to write your solution in the form Function(s) only.
Driver Code to call/invoke your function would be added by GfG's Online Judge.*/
/*
Reverse a linked list
The input list will have at least one element
Return the node which points to the head of the new LinkedList
Node is defined as
struct node
{
int data;
struct Node *next;
}
*/
node *rev_k(node* head,int k)
{
if(head==nullptr) return head;
node *prev,*curr,*temp;
prev=head;
curr=prev->next;
while(--k >0 && curr)
{
if(curr->next) temp=curr->next;
else temp=nullptr;
curr->next=prev;
prev=curr;
curr=temp;
}
return prev;
}
struct node *reverse (struct node *head, int k)
{
if(head==nullptr) return head;
node *f_node,*last_node;
f_node=head;
last_node=head;
int j=k;
while(j-- >0 && last_node) last_node=last_node->next;
node *last=rev_k(head,k);
f_node->next=reverse(last_node,k);
return last;
}
code:--
/*
Please note that it's Function problem i.e.
you need to write your solution in the form Function(s) only.
Driver Code to call/invoke your function would be added by GfG's Online Judge.*/
/*
Reverse a linked list
The input list will have at least one element
Return the node which points to the head of the new LinkedList
Node is defined as
struct node
{
int data;
struct Node *next;
}
*/
node *rev_k(node* head,int k)
{
if(head==nullptr) return head;
node *prev,*curr,*temp;
prev=head;
curr=prev->next;
while(--k >0 && curr)
{
if(curr->next) temp=curr->next;
else temp=nullptr;
curr->next=prev;
prev=curr;
curr=temp;
}
return prev;
}
struct node *reverse (struct node *head, int k)
{
if(head==nullptr) return head;
node *f_node,*last_node;
f_node=head;
last_node=head;
int j=k;
while(j-- >0 && last_node) last_node=last_node->next;
node *last=rev_k(head,k);
f_node->next=reverse(last_node,k);
return last;
}
No comments:
Post a Comment