Reverse a linked list
In recursive code it takes memory for variable and pointer / reference to that memory , hence it needs more memory.
Recursive Code:
class gfg
{
Node temp=null;
Node reverse(Node head,Node prev)
{
if(head.next==null)
{
temp=head;
temp.next=prev;
return temp;
}
else
{
Node next=head.next;
head.next=prev;
return reverse(next,head);
}
}
Node reverse(Node head)
{
return reverse(head,null);
}
}
Node reverse(Node head)
{
Node prev=null;
Node itr=head.next;
temp=head;
temp.next=prev;
while(itr!=null)
{
Node t=itr;
itr=itr.next;
Node x=temp;
temp=t;
temp.next=x;
}
return temp;
}
Recursive Code:
class gfg
{
Node temp=null;
Node reverse(Node head,Node prev)
{
if(head.next==null)
{
temp=head;
temp.next=prev;
return temp;
}
else
{
Node next=head.next;
head.next=prev;
return reverse(next,head);
}
}
Node reverse(Node head)
{
return reverse(head,null);
}
}
Iterative approach:
Node reverse(Node head)
{
Node prev=null;
Node itr=head.next;
temp=head;
temp.next=prev;
while(itr!=null)
{
Node t=itr;
itr=itr.next;
Node x=temp;
temp=t;
temp.next=x;
}
return temp;
}
0 Comments:
Post a Comment