TypeScript封装栈结构和队列结构

649 阅读1分钟

一、栈

我们都知道栈是遵循先进后出原则的,这里我们基于ts的类来封装一个简单的栈结构:

class Stack<T> {
  item: T []
  constructor() {
    this.item = [];
  }
  /*1.插入方法--*/
  insert(value:T) {
    this.item.push(value);
  }
  /*2.取出方法*/
  pop() {
    return this.item.pop();
  }
  /*3.查看栈顶元素*/
  peek() {
    return this.item[this.item.length - 1];
  }
  /*4.返回栈的长度*/
  size() {
    return this.item.length;
  }
  /*5.返回指定元素的索引下标*/
  indexOf(value:T) {
    return this.item.indexOf(value);
  }
  /*6.判断栈是否为空*/
  isEmpty() {
    return this.item.length === 0;
  }
  /*7.格式化方法*/
  toString() {
    let res = '';
    for(let i = 0; i < this.item.length; i++) {
      res +=  this.item[i] + ' '  ;
    }
    return res;
  }
}

二、队列

同样地,队列是遵循先进先出原则:

class Queue<U> {
  item: U []
  constructor() {
    this.item = [];
  }
  //1.插入元素
  enqueue(value: U) {
    this.item.push(value);
  }
  //2.拿出队列前端的元素
  delqueue() {
    return this.item.shift();
  }
  //3.查看队列前端的值
  peek() {
    return this.item[0];
  }
  //4.判断队列是否为空
  isEmpty() {
    return this.item.length === 0;
  }
  //5.返回队列中元素的个数
  size() {
    return this.item.length;
  }
  //6.格式化方法
  toString() {
    let res = '';
    for(let i = 0; i < this.item.length; i++) {
      res += this.item[i] + ' ';
    }
    return res;
  }
}