HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMinor

Get nth node from end in a linked list

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
nthnodegetendlistfromlinked

Problem

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

Solution

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

Code Snippets

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;

Context

StackExchange Code Review Q#150660, answer score: 9

Revisions (0)

No revisions yet.