Sunday, January 1, 2012

How To Print a Linked List in Reverse Order

The question is simple, print the contents of a linked list in reverse order. The question can be easily solved, the trick (as always) is to solve it efficiently. Let's first analyze the minimum time complexity that can be achieved. Since we have to print the contents of the list, the tie complexity cannot be lesser than O(n) where n is the number of nodes. The minimum space complexity can be O(1) which will be achieved as I move further and further.

The first and easiest way to think about solving this problem is recursion. Observe the following code (warning - all untested code):

void printRev(Node * root)
{
if(root==NULL)
return;
printRev(root->next);
printf("%d", &root->info);
}

But the usual problem with recursion - it uses stack space which we don't want it to. Moreover you might run out of space.

So a method I could come up with of O(n) tie complexity and O(1) space complexity is reversing the linked list, printing the info in the normal order and then reversing the linked list again (to ensure you've not changed your actual data). Since we are reversing and want to have O(1) space complexity obviously we cannot use a method for reversing that utilizes space greater than O(1). Hence I'm using the three pointer method to reverse the linked list.
The code for reversing and then printing:

void RevLL(Node * head)
{
Node *p, *q, *r;
if(head == NULL)
{
return;
}
p = head;
q = p->next;
p->next = NULL;
while (q != NULL)
{
r = q->next;
q->next = p;
p = q;
q = r;
}
head = p;
}


void printLL(Node * head)
{
if(head==NULL)
return;
Node * tmp= head;
while(tmp!=NULL){
printf("%d", tmp->info);
tmp=tmp->next;
}
}
void printRev(Node * head)
{
RevLL(head);
printLL(head);
RevLL(head);
}

Again a warning, the above code is untested and there will probably be bugs in it but my main intention was to develop the algorithm.
If someone has an idea to print the contents in reverse order without reversing the linked list and in one pass, they're very welcome.

0 comments: