Questions d'entretien
Entretien pour Linux Kernel Software Engineer
-
AmazonPrint last n nodes of a linked list you only have pointer to Head
Réponses aux questions d'entretien
3 réponse(s)
I suggest to create additional pointer which is the tail. Set a gap of the n nodes between the head and tail, move both, and once the tail points to null it’s the end of the list. Then, move only the head and print the node until it reaches the tail
Utilisateur anonyme le
Actually, that could work but it's too expensive. I suggest you to reverse the list which take O(n) time complexity afterward print first m element and reverse the list back which in total cost you O(n) time complexity and O(1) extra space
Utilisateur anonyme le
Use a queue. Traverse the list and add each element to the queue. Always check if the size of the queue is n, if so then remove the first element before adding a new one. When you finish traversing the list your queue will have exactly the last n elements of the list, just print them in order.
Utilisateur anonyme le