Find third element from last in linked list

Ujjwal Gupta
1 min readJan 3, 2021

--

Finding third element from last requires that you keep a variable and assign it to root element and increment it when length of linked list is greater than equal to 3.

class Node {
constructor(value) {
this.data = value;
this.next = null;
}
}
class LinkedList { add(value) {
const node = new Node(value);
let current = this.root;
if (current == null) {
this.root = node;
} else {
while (current.next != null) {
current = current.next;
}
current.next = node;
}
}
findThirdFromEnd() {
let third;
let current = this.root;
let length = 0;
while (current != null) {
if (length >= 3) {
third = third.next;
} else {
third = this.root;
}
current = current.next;
++length;
}
if (length >= 3) {
return third.data;
}
}
}
const list = new LinkedList();
list.add(1);
list.add(2);
list.add(3);
list.add(4);
list.add(5);
console.log("third element from end", list.findThirdFromEnd())

--

--

Ujjwal Gupta
Ujjwal Gupta

Written by Ujjwal Gupta

Building starscolab | Ex - Frontend lead Polygon | Creator of jsstore, fortjs | opensource creator | we3, blockchain, solidity | javascript

No responses yet