Search

Sponsored Links

Meta

Categories

Archives

Recent Posts

RSS Feeds

06
May

Printing linked List in Reverse without Reversing The List Actually

Related Blog Items

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

1 Comment

  • Alek  said:

    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?


Leave a comment

*
To prove you're a person (not a spam script), type the security word shown in the picture.
Anti-spam image