ProAnswers.org

How to print the reverse order of nodes in a link list

How to print the reverse order of nodes in a link list

An implementation in C would be something as:

typedef struct node
{
int item;
struct node *next;
}node;

  1. void print(node *head)
  2. {
  3. node *move, *n1;
  4. move=head;
  5. if(move==NULL) return;
  6. n1=NULL;
  7. for(;n1!=head;)
  8. {
  9. move=head;
    10.for(;move->next!=n1;move=move->next);
    11.printf(ā€œ%dā€, move->item);
    12.n1=move;
    13.}
    14.}

In the outer loop, MOVE is initialized to HEAD and n1 to NULL. After the inner loop ends, MOVE will point to the last element. We print its value. Then the pointer N1 is set to point to the last element. In the next iteration of the outer loop, MOVE is again set to HEAD and MOVE moves till it advances to the second last node. Then we print its value and set N1 to the second last element. It continues till we reach the HEAD.