9
\$\begingroup\$

Description:

You’re given the pointer to the head node of a linked list and a specific position. Counting backwards from the tail node of the linked list, get the value of the node at the given position. A position of 0 corresponds to the tail, 1 corresponds to the node before the tail and so on.

Code:

int GetNode(Node head,int n) {
 // This is a "method-only" submission. 
 // You only need to complete this method. 
 Node current = head;
 int count = 0;
 while (current != null) {
 count++;
 current = current.next;
 }
 current = head;
 for (int i = 0; i < count - n - 1; i++) { // extra -1 to avoid going out of linked list.
 current = current.next;
 }
 return current.data;
}
asked Dec 23, 2016 at 5:54
\$\endgroup\$
1
  • \$\begingroup\$ What if you are passed an empty list (head is null)? How do you want to handle the case of n >= the length of the list? Your code returns the first list element, @janos code will simply fail. In an assignment I would at least want to see that you realized there are potential problems. \$\endgroup\$ Commented Dec 23, 2016 at 11:57

1 Answer 1

9
\$\begingroup\$

Instead of a count variable and reusing current, I think it's neater to use two pointers:

Node runner = head;
for (int i = 0; i < n; i++) {
 runner = runner.next;
}
Node current = head;
while (runner.next != null) {
 runner = runner.next;
 current = current.next;
}
return current.data;

Other than that, your implementation is fine, except for a few tiny style points that are barely worth mentioning, but here we go anyway:

  • The commented out instructions about method-only submissions are unnecessary
  • Add a space after commas in parameter list
answered Dec 23, 2016 at 6:13
\$\endgroup\$
3
  • \$\begingroup\$ I have to agree, a very neat solution indeed. I wonder how to get thinking like that :) \$\endgroup\$ Commented Dec 23, 2016 at 6:33
  • \$\begingroup\$ Me too :-) I saw it once and can't forget about it. \$\endgroup\$ Commented Dec 23, 2016 at 6:34
  • \$\begingroup\$ Implementation in C, Java and Python: geeksforgeeks.org/nth-node-from-the-end-of-a-linked-list \$\endgroup\$ Commented Dec 23, 2016 at 6:43

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.