Mark As Completed Discussion

Good afternoon! Here's our prompt for today.

Let's implement a linked list, a data structure that serves as one of the fundamental building blocks of many other data structures.

Description

A linked list is defined as a lineardata structurewhere each element is a separate object. Each element (we will call it a node) of a list is comprising of two items - the data and a reference to the next node.

Traditionally we have the following LinkedListNode class definition:

JAVASCRIPT
1class LinkedListNode {
2  constructor(val, next = null) {
3    this.val = val;
4    this.next = next;
5  }
6}

We can readily create a entire linked list by writing statements like:

JAVASCRIPT
1const list1 = new LinkedListNode(2);
2list1.next =  new LinkedListNode(3);

This will append the node to the end of our new list, and does the job most of the time. However, what if we wanted to make things cleaner and implement a class to help us append and prepend nodes?

Given the following skeleton for a Linked List class, can you fill in the #append and #prepend methods? We will call .head on an instance of your class to get the head node.

JAVASCRIPT
1class LinkedList {
2  constructor() {
3    this.head = null;
4    this.tail = null;
5  }
6  
7  prepend(value) {}
8  
9  append(value) {}
10};

Constraints

  • The numbers in the node to be added are within the integer limits
  • Expected time complexity for appending and prepending : O(1)
  • Expected space complexity for appending and prepending : O(1)

Try to solve this here or in Interactive Mode.

How do I practice this challenge?

JAVASCRIPT
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment

Here's our guided, illustrated walk-through.

How do I use this guide?