This is the first article I participated in beginners’ introduction

Definition of linked list

A linked list is a collection of nodes, each containing a value for the node itself and a reference to the next node. The following figure shows the structure of a linked list.

Implement list

Now that we know what a linked list is, let’s start implementing a linked list. Next we define the linked list class.

class LinkedList {
  constructor() {
    this.head = null;
    this.count = 0; }}Copy the code

Here we declare the count attribute to represent the number of nodes in the list, and the head attribute to store the first node in the list.

To represent the first Node or any other Node in a linked list, we also need a helper class, which could be called Node. The Node class is the item we want to add to the list. It contains a value property that represents the value of the current Node. And a next attribute, a reference to the next node. The code is shown below.

export class Node {
  constructor(value) {
    this.value = value
    this.next = null}}Copy the code

Now we’ll add some methods to our LinkedList class.

Add a node to the end of the list

There are two cases of adding nodes to the end of a linked list:

  1. The list is empty and the first node is added
  2. The linked list is not empty. Appends a node to the list

Let’s implement this method.

  push(value) {
    const node = new Node(value);
    if (this.head == null) {
      this.head = node;
    } else {
      let current = this.head;
      while(current.next ! =null) {
        current = current.next;
      }
      current.next = node;
    }
    this.count++;
  }
Copy the code

First we pass in value as a value to create a Node. Then we determine if head has a value. If not, we assign the new node directly to it. If there is a value, we first declare a variable current to hold the value of head. Then we use a while loop class to determine whether the next of current has a value. If it does, it indicates that it is not the last node. We assign the next of current to current, and then repeat this operation until we find the current where next is empty. Assign our new Node to him. And finally we have to increase the number of nodes by one.

To be continued…