How do you print all elements of a linked list.
Anonymous
I'd first tell the interviewer that the linked list might have loops. I'll first check if the linked list has loop or not. if yes, find the beginning of the loop and then print the linked list. To find if a linked list has a loop: 1- using two pointers (slow, fast) slow jumps one node and fast jumps two nodes. 2- if slow and fast meet at any node then there is a loop. To find the start of the loop: 3- after slow and fast met at a node, keep fast there and move slow until it comes back to is 4- the number of steps slow took to go back to fast is the length of the loop. 5- reset slow and fast to the beginning of the linked list. 6- move fast number of times = length of the loop. 7- now move slow and fast both one step at the time and when they meet, this is the beginning of the loop. (Because they are apart with n nodes where n is the size of the loop). 8- Print the linked list normally but make sure to not pass the beginning of the loop twice. 9- after all, the question is not easy as it looks ;)
Check out your Company Bowl for anonymous work chats.