Reputation: 143
There are many posts with probably with same question but the problem says it has to be done by
node* reverseList (node * lh)
{
if(lh==NULL)............ ;
else if (lh->next==NULL)...........;
else ...........;
}
the three blanks must be filled the first two are simply
return NULL
and
return lh
repectively
one way could be just to go down and reverse the pointers but in that case how can i keep the tail intact even after backtracking? is it possible at all?
Upvotes: 0
Views: 573
Reputation: 49
Below is an API which does the reversal of a Single linked list, this one of the best algo that i have seen:
void iterative_reverse()
{
mynode *p, *q, *r;
if(head == (mynode *)0)
{ return;
}
p = head;
q = p->next;
p->next = (mynode *)0;
while (q != (mynode *)0)
{
r = q->next;
q->next = p;
p = q;
q = r;
}
head = p;
}
Upvotes: 1
Reputation: 764
I think this answers it:
node *reverseList(node *lh)
{
if (!lh) return NULL;
else if (!lh->next) return lh;
else {
node *new_head = reverseList(lh->next);
lh->next->next = lh;
lh->next = NULL;
return new_head;
}
}
It returns the head of the reversed list, i.e. the tail of the original list.
head = reverse_list(head);
Upvotes: 2
Reputation: 726849
The trick to solving recursive problems is to pretend that you are done already. To solve this homework by yourself, you need to answer three questions:
lh
set to NULL
)?You answered the first two already: NULL
and lh
are the right answers. Now think of the third one:
else {
node *reversedTail = reverseList(lh->next);
...
}
At this point, reversedTail
contains pre-reversed tail of your list. All you need to do is set lh->next to NULL, add it to the back of the list that you are holding, and return reversedTail
. The final code looks like this:
else {
node *reversedTail = reverseList(lh->next);
node *p = reversedTail;
while (p->next) p = p->next;
p->next = lh;
lh->next = NULL;
return reversedTail;
}
Upvotes: 3