图解栈结构
常见的使用栈的场景
常见的栈操作
JS通过数组实现一个栈结构
const assert = require('assert')
class Stack {
constructor() {
this.items = []
}
push(item) {
return this.items.push(item)
}
pop() {
return this.items.pop()
}
peek() {
return this.items[this.size() - 1]
}
size() {
return this.items.length
}
isEmpty() {
return this.size() === 0
}
clear() {
this.items = []
}
}
// test case
const s = new Stack()
s.push(1)
s.push(2)
assert.strictEqual(s.size(), 2)
s.pop()
assert.strictEqual(s.size(), 1)
s.push(3)
assert.strictEqual(s.peek(), 3)
s.clear()
assert.strictEqual(s.size(), 0)
实例演示
进制转换
const assert = require('assert');
class Stack {
constructor() {
this.items = []
}
push(item) {
return this.items.push(item)
}
pop() {
return this.items.pop()
}
peek() {
return this.items[this.size() - 1]
}
size() {
return this.items.length
}
isEmpty() {
return this.size() === 0
}
clear() {
this.items = []
}
}
function hexConverse(s1, base) {
let result = ''
const s = new Stack()
while (s1) {
s.push(s1 % base)
s1 = Math.floor(s1 / base)
}
while (s.size()) {
result += s.pop()
}
return result
}
assert.strictEqual(hexConverse(10, 2), '1010')
PS:图片资源来源于网络
有兴趣的请关注我的公众号