一、认识栈结构
二、 实现栈结构的两种方式
1.基于数组实现
2.基于链表实现
三、栈的操作
四、实现代码
<script>
//封装栈类
function Stack() {
// 栈中的属性
this.items = []
// 栈相关的操作
// 1.将元素压入栈
// this.push = function () { }
//利用原型
Stack.prototype.push = function (element) {
this.items.push(element)
}
// 2.从栈中取出元素
Stack.prototype.pop = function () {
return this.items.pop();
}
// 3.查看下一栈定元素
Stack.prototype.peek = function () {
return this.items[this.items.length - 1]
}
// 4.判断栈是否为空
// 3.查看下一栈定元素
Stack.prototype.isEmpty = function () {
return this.items.length == 0;
}
// 5.获取栈中元素的个数
Stack.prototype.size = function () {
return this.items.length;
}
// 6.toString();方法
Stack.prototype.toString = function () {
//20 10 12 8 7
var resultString = '';
for (var i = 0; i < this.items.length; i++) {
resultString += this.items[i] + ' '
}
return resultString;
}
}
/*栈的使用
var s =new Stack()
s.push();压栈
s.pop();弹栈 */
var s =new Stack()
s.push(20);
s.push(10);
s.push(100);
s.push(77);
alert(s);
s.pop();
s.pop();
alert(s);
alert(s.peek());
alert(s.size())
</script>
五、结果
备注:个人的学习笔记,记录一下自己的学习经历。