js实现复杂数据结构之Stack

前言

Stack是一种特殊的列表,具有后入先出的特点,任何不在栈顶的元素都无法访问,要得到栈底的元素,必须先拿掉上面的元素。

定义

首先我们还是先对Stack进行定义以及抽象,本例仍然使用数组作为数据源

1.属性

  • 数据源
    _dataSource
  • 栈顶在数组的位置
    top

2.方法

  • 入栈
    push
  • 出栈
    pop
  • 返回栈顶元素
    peek
  • 返回栈内元素个数
    getSize
  • 清空栈
    clear

实现Stack类

class Stack{
  private _dataSource: Array;
  private _top: number;

  constructor() {
    this._top = 0;
    this._dataSource = [];
  }
  public push = () => { }
  public pop = () => { }
  public peek = () => { }
  public clear = () => { }
  public getSize = () => { }
}

实现方法

  • push
    向数组中添加元素,并让top增加
public push = (element: T): void => {
    this._dataSource.push(element);
    this._top++;
  }
  • pop
    向数组中删除元素,并让top减少
public pop = (): T => {
    this._top--;
    return this._dataSource.pop();
  }
  • peek
    返回栈顶元素
public peek = (): T => {
    return this._dataSource[this._top - 1];
  }
  • getSize
    返回栈内元素个数
public getSize = (): number => this._top;
  • clear
    清空栈
public clear = (): void => {
    this._top = 0;
    this._dataSource = [];
  }

完整实例请见github

你可能感兴趣的:(js实现复杂数据结构之Stack)