06
May
Printing linked List in Reverse without Reversing The List Actually
Related Blog Items
- Reversing a circular single linked list using pointers
- Reversing a double linked list
- Reversing a single linked list using stack
- Reversing single linked list recursively
- Reverse linked list using pointers
Printing a linked list in reverse order without actually reversing the linked list can be done by a recursive routine or using a stack.
Lets us see a recursive routine first…
In recursive routine go to the end then print the nodes, i.e. recursive call comes before printing the node… Here is the function…
void printreverse(Node *node) { if (node) { printreverse(node->next); printf("%d -> ",node->info); } }
Reversing the list using stack:
Push all the nodes, pop one by one and print them… Here is the program for this..
void printreverse(Node* node) { Node *tmpnode; Stack *stack = CreateStack(); while(node) { Push(stack, node); node = node->next; } tmpnode = Pop(stack); while(tmpnode) { tmpnode = Pop(stack); printf("%d -> ", tmpnode->info); } DestroyStack(stack); }
Popularity: 36%
You need to log on to convert this article into PDF
Related Blog Items - Reversing a circular single linked list using pointers
- Reversing a double linked list
- Reversing a single linked list using stack
- Reversing single linked list recursively
- Reverse linked list using pointers
Related Blog Items
- Reversing a circular single linked list using pointers
- Reversing a double linked list
- Reversing a single linked list using stack
- Reversing single linked list recursively
- Reverse linked list using pointers
wouldn’t the stack version not print the last element in the list but would instead start with the second to last since,
tmpnode = Pop(stack);
//here tmpnode is the last node
while(tmpnode)
{
tmpnode = Pop(stack);
// now tempnode is the 2nd to last node
printf(”%d -> “, tmpnode->info);
}
to fix this just add a printf(”%d -> “, tmpnode->info); before the while loop
right?
August 13th, 2008 at 5:26 am