Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

第 60 期(数据结构-栈):栈和栈的模拟 #63

Open
wingmeng opened this issue Jul 15, 2019 · 0 comments
Open

第 60 期(数据结构-栈):栈和栈的模拟 #63

wingmeng opened this issue Jul 15, 2019 · 0 comments

Comments

@wingmeng
Copy link
Collaborator

概念:
栈是一种线性数据结构,遵从后进先出(LIFO)原则的有序集合,一个栈可以对数据按照顺序进行组织和管理。
新添加的或是待删除的元素都保存在栈的末尾。我们称作栈顶,而另一端我们称作栈底。

理解:
我们可以把栈想象为只有一端开口的管子,我们可以往管子里塞球,塞进去的球会朝底部方向堆积,这个操作称为 入栈
当我们需要取出球时,肯定只能从开口的一侧开始取,取球的操作称为 出栈
最外侧的球是最后一个放进去的,它被先取出来,这称作 后进先出

image

栈的模拟:

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

  // 添加一个(或几个)新元素到栈顶
  push(element) {
    items.push(element);
  }

  // 移除栈顶的元素,同时返回被移除元素
  pop() {
    return items.pop();
  }

  // 返回栈顶元素,但不对栈做修改
  peek() {
    return items[items.length-1];
  }

  // 判断是否为空栈(没有任何元素)
  isEmpty() {
    return items.length === 0;
  }

  // 返回栈里的元素个数
  size() {
    return items.length;
  }

  // 清空栈
  clear() {
    items = [];
  }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant