Explorer
Node.js

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; } } ```

Implement a Linked List

Medium
Implement a simple singly linked list with `append(val)`, `toArray()`, and `size()` methods.
Editor
Loading Editor...
Evaluate code
Output:Click "Run" above to execute and verify your code here.
{"array":[1,2,3],"size":3}