JS数据结构–双端队列

  • Post author:
  • Post category:其他




双端队列

内容来自这本书

方法 效果
addFront(element) 该方法在双端队列前端添加新的元素。
addBack(element) 该方法在双端队列后端添加新的元素(实现方法和Queue类中的enqueue方法相同)。
removeFront() 该方法会从双端队列前端移除第一个元素(实现方法和Queue类中的dequeue方法相同)。
removeBack() 该方法会从双端队列后端移除第一个元素(实现方法和Stack类中的pop方法一样)。
peekFront() 该方法返回双端队列前端的第一个元素(实现方法和Queue类中的peek方法一样)。
peekBack() 该方法返回双端队列后端的第一个元素(实现方法和Stack类中的peek方法一样)。
class Deque{
    // 一个对象来存储数据
    items = {}
    // 记录队头元素的指针
    head = 0
    // 记录队尾元素的指针
    last = 0
    
    addFront(e){
      if(this.head===0){
        console.log('无法在队头添加了')
        return;
      }
      for(let i=this.last;i>=this.head;i--){
        this.items[i]=this.items[i-1]
      }
      this.head--
    }
  
    addBack(e){
      this.items[this.last] = e
      this.last++
    }
  
    removeFront(){
      if(this.isEmpty()){
        return;
      }
      let res = this.items[this.head]
      delete this.items[this.head]
      this.head++
      return res
    }
  
    removeBack(){
      if(this.isEmpty()){
        return;
      }
      let res = this.items[this.last]
      delete this.items[this.last]
      this.last--
      return res
    }
  
    peekFront(){
      return this.items[this.head]
    }
  
    peekBack(){
      return this.items[this.last]
    }
  
    isEmpty(){
      return this.last === this.head
    }
  
    get size(){
      return this.last-this.head
    }
          
}

回文字符串判定

// 回文字符串判定
const palindrome = function(str){
  let deq = new Deque()
  str = str.toLowerCase()   // 都转为小写(根据判定需求决定是否需要)
  for(let i of str){    // for..of 循环字符串
    deq.addBack(i)      //  全部加入队列中
  }
  while(deq.size>1){
    if(deq.removeFront()!=deq.removeBack()){
      return false;
    }
  }
  return true
}

console.log(palindrome('abandon'))   // false
console.log(palindrome('adfgfda'))        // true
console.log(palindrome('ABccFFddFFccBa')) // true
console.log(palindrome('厂水来自上海的海上自来水厂'))  //true



版权声明:本文为m0_46126931原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。