本小节实现的内容
创建我们自己的
JavaScript
数据结构库
栈数据结构
向栈添加元素
从栈移除元素
如何使用
Stack
类
十进制转二进制
1.栈数据结构
栈是一种遵从
后进先出
(
LIFO
)原则的有序集合。新添加或待删除的元素都保存在栈的同
一端,称作栈顶,另一端就叫栈底。在栈里,新元素都靠近栈顶,旧元素都接近栈底。
一个存储东西小箱子 只有一端的出入 (就是说他只有一个口能出入)先存进去的东西 在最底部 ,最后存进去的东西在最顶部 取的时候只能从顶部开始取 所以 俗称先进后出,后进先出
1.1 创建一个基于数组的栈
function Stack(){
this.items=[]
}
//向栈里面添加一个元素
Stack.prototype.push=function (element){
this.items.push(element)
}
//向栈里面移除元素
Stack.prototype.pop=function (){
return this.items.pop()
}
// peek 查看栈顶元素
Stack.prototype.peek=function (){
return this.items[this.items.length-1]
}
Stack.prototype.isEmpty=function (){
return this.items.length ===0
}
Stack.prototype.size=function(){
return this.items.length
}
Stack.prototype.clear=function (){
this.items=[]
}
Stack.prototype.view_Elevments=function (){
if(!this.isEmpty()){
return Array.prototype.join.call(this.items,",")
}
}
let mystack=new Stack()
mystack.push(1)
mystack.push(2)
mystack.push(3)
console.log(mystack.isEmpty());
console.log(mystack.view_Elements());
1.2 创建一个基于对象的栈
function Stack(){
this.count=0
this.items={}
}
Stack.prototype.push=function (element){
this.items[this.count]=element
this.count++
}
Stack.prototype.IsEmpty=function (){
return (this.count===0)
}
Stack.prototype.get_length=function (){
return this.count
}
Stack.prototype.pop=function (){
if (this.IsEmpty()){
return undefined;
}
this.count--
let element = this.items[this.count]
delete this.items[this.count]
return element
}
Stack.prototype.peek=function (){
if (this.IsEmpty()){
return undefined;
}
return this.items[this.count-1]
}
Stack.prototype.clear=function (){
this.count=0
this.items={}
}
因为代码比较简单我就直接用代码实现了