Quick actions

cmd+k|ctrl+k

Navigation

Languages

LinkedList - my implementation

Snippet info

Language

TypeScript

Visibility

public

Author

gigi-bigi

Created

2025-03-24T19:17:21.74747Z

Updated

2025-03-24T19:19:07.880513Z

type SLLNode = {
  value: number;
  next: SLLNode | null;
};

class SinglyLinkedList {
  private head: SLLNode;
  private tail: SLLNode;
  private length;

  constructor(value: number) {
    this.head = {
      value,
      next: null,
    };

    this.tail = this.head;
    this.length = 1;
  }

  append(value: number) {
    const newNode: SLLNode = {
      value,
      next: null,
    };
    let current = this.getNext(this.head);
    
    console.log('current', current);

    if (current) {
        current.next = newNode;
        this.length++;
        this.tail = current.next;
    }
  }

  private getNext(head: SLLNode): SLLNode {
    const next = head.next;
    if (next && next !== null) {
      return this.getNext(next);
    }

    return head;
  }
}

// 10 --> 5 --> 16 --> 20

/**
  let myLinkedList = {
    head: {
      value: 10,
      next: {
        value: 5,
        next: {
          value: 16,
          next: null
        }
      }
    }
  }
 */

const myLinkedList = new SinglyLinkedList(10);
myLinkedList.append(5);
myLinkedList.append(16);
myLinkedList.append(20);
console.log(myLinkedList);
INFO