Reverse LL In K group
Idea is to save head of LL
reverse LL for first k elements
change next of head to head of reverse LL (next group)
Code:
Node reverse(Node head,int k)
{
if(head==null)
return null;
int c=0;
Node h=head; //saving head
Node prev=null,next;
//reverse
while(c<k && head!=null)
{
next=head.next;
head.next=prev;
prev=head;
head=next;
++c;
}
//reverse next group as next is now pointing to k+1th node
if(next!=null)
h.next=reverse(next,k);
//return head of reversed LL
return prev;
}
reverse LL for first k elements
change next of head to head of reverse LL (next group)
Code:
Node reverse(Node head,int k)
{
if(head==null)
return null;
int c=0;
Node h=head; //saving head
Node prev=null,next;
//reverse
while(c<k && head!=null)
{
next=head.next;
head.next=prev;
prev=head;
head=next;
++c;
}
//reverse next group as next is now pointing to k+1th node
if(next!=null)
h.next=reverse(next,k);
//return head of reversed LL
return prev;
}
0 Comments:
Post a Comment