Tell us what’s happening:
Describe your issue in detail here.
Hi everyone,
I don’t get why I’m failing the tests with the code below,
Failing tests:
- Your LinkedList class should assign head to the first node added.
- The previous node in your LinkedList class should have reference to the newest node created.
Your code so far
class Node {
constructor(element) {
this.element = element;
this.next = null;
}
getNext() {return this.next}
setNext(n) {this.next = n}
};
class LinkedList {
constructor() {
this.length = 0;
this.head = null;
}
getHead() {
return this.head;
};
setHead(N) {
this.head = N;
}
increaseLength() {
this.length++;
}
size(){
return this.length;
};
add(element){
if(this.size() === 0) {
//1st link
let N = new Node(element);
this.setHead(N);
this.increaseLength();
return
}
let tempHead = this.getHead();
while(tempHead.getNext() !== null) {
tempHead = tempHead.getNext();
}
let N = new Node(element);
tempHead.setNext(N);
this.increaseLength();
};
printList() {
let read = this.getHead()
do {
console.log(read)
read = read.getNext()
} while(read)
}
}
let L = new LinkedList
L.add(1)
console.log(L)
L.add(2)
console.log(L)
L.add(3)
console.log(L)
L.add(4)
console.log(L)
L.printList()
// console output
{ length: 1, head: { element: 1, next: null } }
{ length: 2,
head: { element: 1, next: { element: 2, next: null } } }
{ length: 3,
head: { element: 1, next: { element: 2, next: [Object] } } }
{ length: 4,
head: { element: 1, next: { element: 2, next: [Object] } } }
{ element: 1,
next: { element: 2, next: { element: 3, next: [Object] } } }
{ element: 2,
next: { element: 3, next: { element: 4, next: null } } }
{ element: 3, next: { element: 4, next: null } }
{ element: 4, next: null }
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/111.0
Challenge: Data Structures - Create a Linked List Class
Link to the challenge: