Untitled

mail@pastecode.io avatar
unknown
typescript
a year ago
754 B
5
Indexable
Never
type listNode<T> = {
  data: T;
  next: listNode<T> | null;
}

class LinkedList<T> {

  private head: listNode<T>;


  constructor(init: T) {
    this.head = { data: init, next: null }
  }

  hasNext(node: listNode<T>): boolean {
    return node.next != null;
  }
  remove(data: T): void {
    let p = this.head
    while (this.hasNext(p)) {
      if (p.next!.data == data) {
        break;
      }
      p = p.next!
    }
    p.next = null;
  }

  append(data: T): listNode<T> {
    const node: listNode<T> = { data, next: null };
    if (this.head == undefined) { this.head = node }
    let p = this.head;
    while (this.hasNext(p)) {
      p = p.next!
    }
    p.next = node
    return node
  }
  getHead(): listNode<T> {
    return this.head
  }
}