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

Find kth element from tail of singly linked list in one pass

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

Problem

I have tried the below program to find (Kth element from tail) of a singly linked list. I have tried to utilize the length field which I am incrementing whenever an item is added into the list or vice versa.

public Node findKthFromTail(int kthElem) {
    // length has the size of the list
    int kthPos = length - kthElem;

    if (kthPos  node = head;
    int start = 0;
    while (node != null) {
        if (start == kthPos) {
            // found the node
            break;
        }

        node = node.getNext();
        start++;
    }

    return node;
}

Solution

Trust... it's all about trust.

Trust your length is accurate (if it is not, you have other problems).

Then, your code becomes a simple loop:

// length has the size of the list
int kthPos = length - kthElem;

if (kthPos  node = head;
while (kthPos-- > 0) {
    node = node.getNext();
}
return node;

Code Snippets

// length has the size of the list
int kthPos = length - kthElem;

if (kthPos < 0) {
    return null;
}

Node<T> node = head;
while (kthPos-- > 0) {
    node = node.getNext();
}
return node;

Context

StackExchange Code Review Q#91355, answer score: 3

Revisions (0)

No revisions yet.