Created
February 9, 2021 04:22
-
-
Save bishil06/f39e39b89db444db234076ca5fba8921 to your computer and use it in GitHub Desktop.
_JavaScript_stack
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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