javascript - 堆栈问题?

时间:2021-01-08 08:31:04

标签: javascript data-structures stack

当我控制台记录堆栈类时,我想查看已删除元素的堆栈,但程序只是告诉已删除但堆栈仍然相同,

输出

100 加到 0

200 加到 1

500 加到 2

400 添加到 3

800 加到 4

已移除 800 个

Stack {item: Array(5), count: 4} 我希望数组长度为 4

计数:4 项目:数组(5)

0:100 1:200 2:500 3:400 4:800 长度:5

class Stack {
  constructor() {
    this.item = [];
    this.count = 0;
  }

  // Add Elements to stack

  push(element) {
    this.item[this.count] = element;
    console.log(`${element} added to ${this.count}`);
    this.count += 1;
    return this.count - 1;
  }

  pop() {
    if (this.count === 0) return undefined;
    let deleteItem = this.item[this.count - 1];
    console.log(this.count);
    this.count -= 1;
    console.log(`${deleteItem} removed`);
    return deleteItem;
  }
}

let stack = new Stack();

stack.push(100);
stack.push(200);
stack.push(500);
stack.push(400);
stack.push(800);

stack.pop();

console.log(stack);

1 个答案:

答案 0 :(得分:0)

pop类的Stack方法中,需要移除this.item的最后一个元素。请注意,JavaScript 数组已经具有 .push().pop() 方法,因此它们可以作为本机堆栈运行。

class Stack {
  constructor() {
    this.item = [];
    this.count = 0;
  }

  // Add Elements to stack

  push(element) {
    this.item[this.count] = element;
    console.log(`${element} added to ${this.count}`);
    this.count += 1;
    return this.count - 1;
  }

  pop() {
    if (this.count === 0) return undefined;
    let deleteItem = this.item.pop();
    console.log(this.count);
    this.count -= 1;
    console.log(`${deleteItem} removed`);
    return deleteItem;
  }
}

let stack = new Stack();

stack.push(100);
stack.push(200);
stack.push(500);
stack.push(400);
stack.push(800);

stack.pop();

console.log(stack);

相关问题