So, I got this question from the exam.
How can you get nth node from tail in single list?
Each node has a value and the following (which is a pointer to the next value). We are given the following:
getNodeFromTail(Node head, int x) { }
So I did this to find the length of the list by going through it once. Then again you need to get the (length-x) node. Thus, a total of 2 workarounds.
getNodeFromTail(Node head, int x) { int length = 0; Node headdupe = head; while (headdupe.next != NULL) { headdupe = headdupe.next; length++; } int a = length--; for (int y = 0; y < a; y++) { head = head.next; } return head; }
That's right, but there is also a bonus question that asks if we can do the same, but only bypass it once. I could not think about it during the exam, but after I thought about one way, but I'm not too sure about it.
I could create an ArrayList of length x. Then every time I start the while loop, I add an element to the beginning of the array, cascade down and start the last element of the array. Then, when the head goes to zero, return the node to the array [x-1].
Is it correct? Is there a better solution?
source share