top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

C: Write a compact code to reverse the singly linked list using recursion?

+2 votes
567 views

I am looking for sample code which can impress an interviewer.

posted Aug 31, 2016 by Rupam

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

2 Answers

0 votes

I wrote a function and tested. Code is as following:

void rvsLinkedLst(Node *node, Node **newHead)
{
if (node == NULLP || node->next == NULLP)
{
*newHead = node;
return;
}
rvsLinkedLst(node->next, newHead);
node->next->next = node;
node->next = NULLP;
}

answer Sep 3, 2016 by Neeraj Mishra
0 votes

Hi Neeraj, Your code can be optimized as following:

Node* rvsLinkedLst(Node *node)
{
Node *newHead = NULLP;
if (node == NULLP || node->next == NULLP)
{
return node;
}
new Head = rvsLinkedLst(node->next);
node->next->next = node;
node->next = NULLP;
return newHead;
}

answer Sep 4, 2016 by Harshita
...