Skip to content

Instantly share code, notes, and snippets.

@bishil06
Created February 9, 2021 04:22
Show Gist options
  • Save bishil06/f39e39b89db444db234076ca5fba8921 to your computer and use it in GitHub Desktop.
Save bishil06/f39e39b89db444db234076ca5fba8921 to your computer and use it in GitHub Desktop.
_JavaScript_stack
class Stack{
constructor() {
this.list = [];
this.top = null;
}
push(v) {
this.list.push(v);
this.top = v;
}
pop() {
if (this.top === null) {
return null;
}
let r = this.list.pop();
if (!r) {
this.top = null;
}
else {
this.top = this.list[this.list.length-1];
}
return r;
}
peek() {
return this.top;
}
}
let s = new Stack();
s.push(1)
s.push(2)
s.pop();
s.push(3)
s.pop();
console.log(s.peek()); // 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment