Skip to content

Instantly share code, notes, and snippets.

@gladimdim
Created October 20, 2021 12:55
Show Gist options
  • Save gladimdim/b3fe1158c880135873543f4ad0f914b2 to your computer and use it in GitHub Desktop.
Save gladimdim/b3fe1158c880135873543f4ad0f914b2 to your computer and use it in GitHub Desktop.
/// Given a pointer to the head of a linked list and a specific position, determine the data value at that position. Count backwards from the tail node. The tail is at postion 0, its parent is at 1 and so on.
/// https://www.hackerrank.com/challenges/get-the-value-of-the-node-at-a-specific-position-from-the-tail
int? findNthElementInList(Node? head, int n) {
var current = head;
var counter = 0;
Node? result = head;
while (current != null) {
// when we processed nth element in list let's move result pointer to its next object
if (counter > n) {
result = result!.next;
}
// keep track of the amount of processed Nodes
counter++;
current = current.next;
}
return result?.value;
}
void main() {
var l1 = Node<int>(-3, Node(4, Node(5, Node(6, Node(7, Node(8))))));
print(("Find nth element from tail in a ll:"));
print(findNthElementInList(l1, 5)); // -3
print(findNthElementInList(l1, 0)); // 8
print(findNthElementInList(l1, 1)); // 7
print(findNthElementInList(l1, 3)); // 5
print(findNthElementInList(null, 3)); // null
}
class Node<T> {
T value;
Node<T>? next;
Node(this.value, [this.next]);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment