InterviewSolution
| 1. |
Do you need to print a singly linked LinkedList in reverse order in a single traversal? How can you achieve this? Also how to find out the middle element of a linked list? |
|
Answer» A singly linked LinkedList is uni-directional with each node pointing to the next node. ONE of the ways to traverse the list and print it in reverse order in a single go is with the HELP of the Stack data structure. A stack data structure follows Last In First Out (LIFO) order i.e. the last element to be pushed to the stack would be the first element that will be popped out. To print the linked list in reverse order we simply traverse the list and push each element to the stack. Once traversal is COMPLETE we need to pop out each element from the stack until no more element is left. Since the element that gets added last will be the first one to be popped out, the elements will be printed in reverse order. Finding the middle element in a LinkedList is another common problem. To solve it we need to use two POINTERS. One pointer will be moved by one element at a time, while the other pointer will be moved two elements at a time. This way when the SECOND pointer reaches the end of the linked list, the position where the first pointer would be, in the middle of the linked list. |
|