TypeScript: Implement a Linked List

1. Introduction

A Linked List is a fundamental data structure that consists of nodes, where each node contains data and a reference (or link) to the next node in the sequence. In this tutorial, we'll walk through the steps to implement a singly linked list using TypeScript.

2. Program Overview

Our TypeScript program will define classes for the Node and the Linked List itself. We'll then implement some basic operations like adding a node to the end, displaying the list, and finding the length.

3. Code Program

// Define the Node class
class Node {
    value: number;
    next: Node | null = null;

    constructor(value: number) {
        this.value = value;
    }
}

// Define the LinkedList class
class LinkedList {
    head: Node | null = null;

    // Add node to the end of the list
    append(value: number) {
        const newNode = new Node(value);
        if (!this.head) {
            this.head = newNode;
            return;
        }
        let current = this.head;
        while (current.next) {
            current = current.next;
        }
        current.next = newNode;
    }

    // Display the list
    display() {
        let current = this.head;
        while (current) {
            console.log(current.value);
            current = current.next;
        }
    }

    // Find the length of the list
    length(): number {
        let count = 0;
        let current = this.head;
        while (current) {
            count++;
            current = current.next;
        }
        return count;
    }
}

// Test the LinkedList class
const myList = new LinkedList();
myList.append(5);
myList.append(10);
myList.append(15);
console.log("The linked list contains:");
myList.display();
console.log(`The length of the list is: ${myList.length()}`);

4. Step By Step Explanation

1. We begin by defining the Node class. Each node will contain:

- A value of type number that stores the data.

- A next property that points to the next node in the list or is null if there's no next node.

2. Next, we define the LinkedList class which will have:

- A head property that points to the first node in the list or is null if the list is empty.

3. Inside the LinkedList class, we provide the following methods:

  • append: Adds a new node with a given value to the end of the list.
  • display: Prints the values of all nodes in the list from head to tail.
  • length: Returns the number of nodes in the list.

4. We test our LinkedList class by:

  • Creating a new LinkedList.
  • Appending three values (5, 10, and 15).- Displaying the list.
  • Printing the length of the list. 

With this TypeScript implementation, one can easily manage and manipulate a singly linked list.

Comments