TypeScript 实现基于链表的栈

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

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

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

  push(item: Item): void {
    const oldFirst: ListNode<Item> = this.first
    this.first = new ListNode<Item>(item, oldFirst)
    this.N++
  }
  pop(): Item {
    const item: Item = this.first.item
    this.first = this.first.next
    this.N--
    return item
  }
}