Linked list
by tanya_22
HTML
<h1>hi LinkedList! ☀️</h1>
<div class="playground">
<div class="todo">
<input type="checkbox" checked>add (по учебнику)<br>
<input type="checkbox" checked>insertAt(по учебнику) <br>
<input type="checkbox" checked>remove (по учебнику)<br>
<input type="checkbox" checked>removeAt (sam)<br>
<input type="checkbox" checked>findByIndex (sam)<br>
<input type="checkbox" checked>length (по учебнику)<br>
<input type="checkbox" checked>reverse (sam) <br>
<input type="checkbox" checked>convert from array (sam)<br>
<input type="checkbox" checked>convert to array (sam)<br>
</div>
<pre id="linkedList"></pre>
</div>
CSS
body {
background: grey;
}
h1 {
color: #fcbe24;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
}
.playground {
display: flex;
width: 100%;
flex-direction: column;
justify-content: space-around;
}
JavaScript
const linkedListEl = document.getElementById('linkedList');
class LinkedListNode {
constructor(value, next = null) {
this.value = value;
this.next = next;
}
}
class LinkedList {
constructor() {
this.head = null;
}
add(value) {
this.head = new LinkedListNode(value, this.head);
}
insertAt(index, value) {
if (this.head === null) {
this.head = new LinkedListNode(value, null);
} else if (index === 0) {
this.add(value);
} else {
let current = this.head;
while (current.next !== null && index > 1) {
current = current.next;
index = index - 1;
}
current.next = new LinkedListNode(value, current.next);
}
}
remove() {
if (this.head === null) {
console.log('linked list is empty');
return;
}
const head = this.head;
this.head = this.head.next;
return head.value;
}
removeAt(index = 0) {
if (this.head === null) {
console.log('linked list is empty');
return;
}
if (index === 0) {
this.remove();
} else {
let current = this.head;
while (current.next.next !== null && index > 1) {
current = current.next;
index = index - 1;
}
current.next = current.next.next;
}
}
length() {
let length = 0;
if (this.head === null) {
return length;
}
let current = this.head;
while (current !== null) {
current = current.next;
length++;
}
return length;
}
findByIndex(index) {
if (typeof index !== 'number') {
return 'index must be a number';
}
if (this.head === null) {
return 'the linked list is empty';
}
if (index <= 0) {
return this.head.value;
} else {
let current = this.head;
while (current.next !== null && index >= 1) {
current = current.next;
index = index - 1;
}
return current.value;
}
}
reverse() {
if (this.head === null) {
return 'the linked list is empty';
...