Problem:
Printing singly linked list is a little tricky problem because singly linked list only stores address to of the next node, no previous node address is stored in any node.
Logic:
This problem can be solved easily using recursion. Recursively call PrintReverse function till root is not null and start print.
For last node his next is null, so for that null function will return and executing line below recursive call will start execution which will start printing node values. As print line execution starts from last node, linked list will be printed in reverse order.
Implementation:
1 2 3 4 5 6 7 8 |
public void PrintReverse(Node head) { if (head!= null) { PrintReverse(head.next); Console.Write(" " + head.val); } } |