TypeScript 实现基于链表的队列

118 阅读1分钟
class ListNode<Item> {
  public item: Item
  public next: ListNode<Item>
  constructor(item: Item, next: ListNode<Item>) {
    this.item = item
    this.next = next
  }
}

class Queue<Item> {
  private first: ListNode<Item>
  private last: ListNode<Item>
  private N: number
  constructor() {
    this.first = null
    this.last = null
    this.N = 0
  }

  isEmpty(): boolean {
    return this.N === 0
  }
  size(): number {
    return this.N
  }

  enqueue(item: Item): void {
    // 表尾添加
    const oldLast: ListNode<Item> = this.last
    this.last = new ListNode<Item>(item, null)
    if (this.isEmpty()) {
      this.first = this.last
    } else {
      oldLast.next = this.last
    }

    this.N++
  }
  dequeue(): Item {
    // 表头删
    const item: Item = this.first.item
    this.first = this.first.next
    this.N--
    if (this.isEmpty()) {
      this.last = null
    }
    return item
  }
}