Meta Interview Question

How do you print all elements of a linked list.

Interview Answers

Anonymous

Aug 31, 2017

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 ;)

5

Anonymous

May 8, 2014

class Element { int value; Element next; } public void printList(Element root) { if (root == null) return; System.out.println("Value: " + root.value); printList(root.next); }

3

Anonymous

Sep 29, 2014

// Define a structure for linked list element typedef struct ListElmt_ { int *data; struct ListElmt_ *next; } ListElmt; // Define a structure for linked lists typedef struct List_ { int size; ListElmt *head; ListElmt *tail; } List; void printLinkedList(List *list) { ListElmt *currentElement = list->head; while (currentElement != NULL) { printf("%d ", *((int *)currentElement->data)); currentElement = currentElement->next; } }

Anonymous

Nov 30, 2014

I wonder why this question is so much easier than the others I have been reading here? It troubles me that there is so much variability in Facebook's interview questions if this really is the case.

Anonymous

Dec 13, 2014

Maybe they are just labelled incorrectly? some are phone interviews, some are for interns, for collage graduates, for 3-4 years experience, and others are for 4+ years experience. anyway I try to solve as much as I can....

Anonymous

Sep 29, 2013

struct Node{ int value Node *next; } for(Node *ptr = Head; ptr != NULL; ptr = ptr->next) { cout value <