Chegg.com Interview Question
Consultantshi see this code,
node* rev(node *p)//initally p is pointing to starting node
{
if(p->next)
{
rev(p->next)->next=p;
p->next=NULL;
return p;
}
else
{
head=p;
return p;
}
}
addendum:
when you reverse and then traverse the reversed list, you can restore it to the original pointer. So your original list is unharmed because of this reverse output (which is supposed to be read-only).
public class ReverseLinkedListRecursion {
public Node reverse(Node head) {
return reverse(head, head, null);
}
public Node reverse(Node temp, Node current, Node prev) {
if (current.next == null) {
current.next = prev;
return current;
} else {
Node t = current.next;
current.next = prev;
return reverse(t, temp, current);
}
}}
}
- jasmine August 11, 2015