堆栈
- 堆栈的性质
LIFO
push/pop
overflow/underflow - 实现堆栈
- 单元测试
堆栈的性质
实现堆栈
// 堆栈
class Stack{
constructor(max =1000){
//空间
this.data = new Array(max)
//栈顶(栈指针)
this.top = -1
this.max = max
}
push(x){
if(this.top === this.max -1){
throw 'stack overflow'
}
this.top ++
this.data[this.top] = x
}
pop(){
if(this.top === -1){
throw 'stack underflow'
}
const x = this.data[this.top]
this.top --
return x
}
}
module.exports = Stack
单元测试
用到npm中的第三方包,我一般把这种常用的装到全局
全局安装 chai
npm i -g chai
全局安装 mocha
npm i -g mocha
const { assert } = require('chai')
const Stack = require('./stack')
describe('测试堆栈', () => {
it('LIFO', () => {
const s = new Stack(1000)
for (let i = 1; i <= 5; i++) {
s.push(i)
}
assert.equal(s.pop(), 5)
assert.equal(s.pop(), 4)
assert.equal(s.pop(), 3)
assert.equal(s.pop(), 2)
assert.equal(s.pop(), 1)
})
it('stack overflow-1', () => {
const s = new Stack(1000)
let error = null
try {
for (let i = 0; i < 1001; i++) {
s.push(i)
}
} catch (ex){
error = ex
}
assert.equal(error,'stack overflow')
})
it('stack overflow-2', () => {
const s = new Stack(1000)
let error = null
try {
for (let i = 0; i < 999; i++) {
s.push(i)
}
} catch (ex){
error = ex
}
assert.equal(error,null)
})
it('stack underflow', () => {
const s = new Stack()
let error = null
try{
s.pop()
}catch(ex){
error=ex
}
assert.equal(error,'stack underflow')
})
it('性能测试',()=>{
const s = new Stack(1000000)
const t = new Date().getTime()
for(let i = 0;i<1000000;i++){
s.push(i)
}
assert.equal(
new Date().getTime() - t < 50,
true,
"性能不达标"
)
})
})
通过 mocha 运行这个js
这个是已经我调试好的,例子是我自己想用的,如果想要一点没问题都没,就用用例了,想leetcode里面一样