[Updated] Goldman Sachs Aptitude Test Questions and Answers
Practice List of TCS Digital Coding Questions !!!
Take 50+ FREE!! Online Data Interpretation Mock test to crack any Exams.
Interview Questions and Answers :: Cisco

2. Write a code for reversing a linked list, recursive and non-recursive.

Answer:

Non-Recursive
========

void reverse(struct node ** head)
{
struct node* prev = NULL;
struct node* current = *head;
struct node* next;
while (current != NULL)
{
next = current->next;
current->next = prev;
prev = current;
current = next;
}
*head = prev;
}
This trick might help you
there are three pointer ( prev, current, next)
next = current*
current* = prev
prev = current
current = next

if we see from above logic then before = is like top to bottom then bottom to top .
* marked pointer will have next.

Recursive
=======


struct node * recLinkedList(struct node *head, struct node *prev)
{
struct node *tmp = head->next;
head->next = prev;
if ( tmp != NULL)
recLinkedList(tmp, head);

return head
}

int main()
{
struct node *head = recLinkedList (head, NULL);
}

Post Your Answer Here:      Public      Private

Rate This: +1 -0
Report     

Post Your Reply Here:     

Report Error

Report Error

Please Login First Click Here