found good totorial on youtube similar to article “how to implement a LinkedList in javascript” which is on freecodecamp site, but they have some differences so I wanted to ask if someone can me help
on freecodecamo site it go like this:
class ListNode {
constructor(data) {
this.data = data
this.next = null
}
}
class LinkedList {
constructor(head = null) {
this.head = head
}
}
let node1 = new ListNode(2)
let node2 = new ListNode(5)
node1.next = node2
let list = new LinkedList(node1)
console.log(list) prints:
head: Linstnode { data: 2, next: ListNode { data: 5, next: null } }
this is version from freecodecamp site, there is explained how to getLas, getFirst, getSize and clear method but not insertFirst, insertLast and insertAt…
Question is is there another way of inserting new value/element to list other than explained in tutorial? In tutorial is explained inseringFirst throught function, like this:
class ListNode {
constructor(data) {
this.data = data
this.next = null
}
}
class LinkedList {
constructor(head = null) {
this.head = head
}
}
insertFirst(data){
this.head = new ListNode(data, this.head);
}
let list = new LinkedList()
console.log(list); displays: LinkedList { head: ListNode { data: 100, next: null} }
in second example I deleted
let node1 = new ListNode(2);
let node2 = new ListNode(5);
node1.next = node2;
but is there way with next method to make more then one next like that we could make
let node 1
let node 2
let node 3
let node 4
and with next method make them in order one to another,
Question is… is second example only way of inserting fiirst or last items
and in insertFirst function is its parametar (data) reffered to class’s ListNode data parameter and its this.head reffered to class’s LinkedList constructor this.head?
thank You