实现基本的栈结构,代码如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>栈</title>
</head>
<body>
<script type="text/javascript">
function Stack() {
this.item = []
//进栈
Stack.prototype.push = data => this.item.push(data)
//出栈
Stack.prototype.pop = () => this.item.pop()
//查询是否为空
Stack.prototype.isEmpty = () => this.item.length === 0
//查询第一个
Stack.prototype.peek = () => this.item[this.item.length -1]
//查询长度
Stack.prototype.size = () => this.item.length
//toString方法
Stack.prototype.toString = () => {
let res = ''
for( let i in this.item) {
res += this.item[i] + ' '
}
return res
}
}
let s = new Stack()
s.push(123)
s.push(456)
s.push(789)
s.push(321)
s.push(6547)
s.push(987)
s.push(0)
console.log(s)
s.pop()
s.pop()
console.log(s)
console.log(s.peek())
console.log(s.isEmpty())
console.log(s.size())
console.log(s.toString())
</script>
</body>
</html>
效果图:

本文介绍了一个使用JavaScript实现的基本栈结构。栈是一种后进先出(LIFO)的数据结构,主要功能包括进栈、出栈、查询是否为空、查询栈顶元素、获取栈的长度以及转换为字符串表示。通过具体实例展示了栈的操作过程。
1249

被折叠的 条评论
为什么被折叠?



