JavaScript 程序:实现栈

要理解此示例,您应了解以下 JavaScript 编程 主题


栈是一种遵循后进先出 (LIFO) 原则的数据结构。最后添加的元素最先被访问。这就像把书叠在一起。你最后放的书最先被拿出来。


示例:实现栈

// program to implement stack data structure
class Stack {
    constructor() {
        this.items = [];
    }
    
    // add element to the stack
    add(element) {
        return this.items.push(element);
    }
    
    // remove element from the stack
    remove() {
        if(this.items.length > 0) {
            return this.items.pop();
        }
    }
    
    // view the last element
    peek() {
        return this.items[this.items.length - 1];
    }
    
    // check if the stack is empty
    isEmpty(){
       return this.items.length == 0;
    }
   
    // the size of the stack
    size(){
        return this.items.length;
    }
 
    // empty the stack
    clear(){
        this.items = [];
    }
}

let stack = new Stack();
stack.add(1);
stack.add(2);
stack.add(4);
stack.add(8);
console.log(stack.items);

stack.remove();
console.log(stack.items);

console.log(stack.peek());

console.log(stack.isEmpty());

console.log(stack.size());

stack.clear();
console.log(stack.items);

输出

[1, 2, 4, 8]
[1, 2, 4]
4
false
3
[]

在上面的程序中,创建了Stack类来实现栈数据结构。类方法如add()remove()peek()isEmpty()size()clear()都已实现。

使用new运算符创建了一个栈对象,并通过该对象访问了各种方法。

  • 这里,最初 this.items 是一个空数组。
  • push()方法将一个元素添加到 this.items
  • pop()方法从 this.items 中移除最后一个元素。
  • length属性获取 this.items 的长度。

另请阅读

你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战