Implement a simple singly linked list with `append(val)`, `toArray()`, and `size()` methods.
Problem Statement
Implement a simple singly linked list with `append(val)`, `toArray()`, and `size()` methods.
Complexity
Time Complexity: -
Space Complexity: -
Hints
š” Hint 1:
A linked list consists of nodes, each with a value and a next pointer.
š” Hint 2:
Keep track of the head node and traverse to the end for append.
š” Hint 3:
Create a Node class with value and next. LinkedList has head and a size counter.
ā
Solution:
```javascript
class LinkedList {
constructor() { this.head = null; this._size = 0; }
append(val) {
const node = { value: val, next: null };
if (!this.head) { this.head = node; } else {
let curr = this.head;
while (curr.next) curr = curr.next;
curr.next = node;
}
this._size++;
}
toArray() {
const arr = []; let curr = this.head;
while (curr) { arr.push(curr.value); curr = curr.next; }
return arr;
}
size() { return this._size; }
}
```