2018-08-01 js栈与队列补充

2018-08-01  本文已影响0人  LilacSun

栈与队列之js(ts)手写(补充)

interface ObjectT {

  value: string,

}

class Stack {

  private stackContent: ObjectT[]

  private stackTop?: ObjectT

  private objectNumber: number

  constructor(stack:ObjectT[]) {

    this.stackContent = stack || []

    this.objectNumber = this.stackContent.length

    if(this.objectNumber != 0) {

      this.stackTop = this.stackContent[0]

    }

  }

  public push(obj: ObjectT) {

    this.objectNumber++

    for(let i = this.objectNumber-1;i >= 0;i--) {

      if(i == 0) {

        this.stackContent[i] = obj

      }

      else {

        this.stackContent[i] = this.stackContent[i-1]

      }

    }

    this.stackTop = this.stackContent[0]

    console.log(this.stackContent)

    console.log(this.stackTop)

  }

  public pop() {

    if(this.objectNumber > 0) {

      for(let i = 0;i < this.objectNumber-1;i++) {

        this.stackContent[i] = this.stackContent[i+1]

      }

      let result = this.stackTop

      this.stackTop = this.stackContent[0]

      delete this.stackContent[this.objectNumber-1]

      this.objectNumber--

      return result

    }

  }

}

class Queue {

  private queueContent: ObjectT[]

  private queueTop?: ObjectT

  private queueTail?: ObjectT

  private objectNumber: number

  constructor(queue: ObjectT[]) {

    this.queueContent = queue || []

    this.objectNumber = this.queueContent.length

    if(this.objectNumber != 0) {

      this.queueTop = this.queueContent[0]

      this.queueTail = this.queueContent[this.objectNumber-1]

    }

  }

  public push(obj:ObjectT) {

    this.objectNumber++

    for(let i = this.objectNumber-1;i >= 0;i--) {

      if(i == 0) {

        this.queueContent[i] = obj

      }

      else {

        this.queueContent[i] = this.queueContent[i-1]

      }

    }

    this.queueTop = this.queueContent[0]

    this.queueTail = this.queueContent[this.objectNumber-1]

    console.log(this.queueContent)

    console.log(this.queueTop)

    console.log(this.queueTail)

  }

  public pop() {

    if(this.objectNumber > 0) {

      let result = this.queueTail

      delete this.queueContent[this.objectNumber-1]

      this.objectNumber--

      this.queueTail = this.queueContent[this.objectNumber-1]

      console.log(this.queueContent)

      return result

    }



  }

}
上一篇下一篇

猜你喜欢

热点阅读