我爱编程

js实现复杂数据结构之List

2018-03-03  本文已影响0人  summer_味道制造

前言

List是一组有序的数据,我们将List中的每个数据称之为元素。

定义

在设计一个数据结构之前,首先我们需要对其进行抽象,给出List的定义,List应该有什么属性以及什么方法,这个例子中,我们将使用javaScrip数组来作为数据源(近期在学习typeScript,所以以下例子使用ts实现,如想查看js版,请访问gitHub)

1.属性

  1. 方法

实现List类

class List<T> {
  private _length: number;
  private _index: number;
  private _dataSource: Array<T>;

  public clear = () => { }
  private _find = () => { }
  public toString = () => { }
  public insert = () => { }
  public add = () => { }
  public remove = () => { }
  public front = () => { }
  public end = () => { }
  public prev = () => { }
  public next = () => { }
  public hasPrev = () => { }
  public hasNext = () => { }
  public getSize = () => { }
  public getIndex = () => { }
  public moveTo = () => { }
  public getElement = () => { }
  public contains = () => { }
}

实现方法

public add = (element: T): void => {
    this._dataSource[this._length] = element;
    this._length++;
  }
public remove = (element: T): boolean => {
    const index = this._find(element);
    if (index > -1) {
      this._dataSource.splice(index, 1);
      this._length--;
      return true;
    }
    return false;
  }
public clear = (): void => {
    this._dataSource.length = 0;
    this._length = 0;
    this._index = 0;
  }
public contains = (element: T): boolean => {
    const index: number = this._find(element);
    if (index > -1) return true;
    return false;
  }
 public front = (): void => {
    this._index = 0;
  }
  public end = (): void => {
    this._index = this._length - 1;
  }
  public prev = (): void => {
    if (this._index > 0) this._index --;
  }
  public next = (): void => {
    if (this._index < this._length) this._index ++;
  }
  public hasPrev = (): boolean => {
    return this._index >= 0;
  }
  public hasNext = (): boolean => {
    return this._index < this._length;
  }
  public getSize = (): number => {
    return this._length;
  }
  public getIndex = (): number => {
    return this._index;
  }
  public moveTo = (newIndex): number => {
    return this._index = newIndex;
  }
  public getElement = (): T => {
    return this._dataSource[this._index];
  }

到目前为止就已经实现了List的所有方法,下面让我们来使用这个List

const list = new List<string>();
list.add('a');
list.add('b');
list.add('c');
for (list.front(); list.hasNext(); list.next()) {
  console.log('element', list.getElement())
}
上一篇 下一篇

猜你喜欢

热点阅读