JavaScript栈和队列相关操作与实现方法详解
本文实例讲述了JavaScript栈和队列相关操作与实现方法。分享给大家供大家参考,具体如下:
一、栈的介绍
栈就是和列表类似的一种数据结构,数据只能在栈顶添加或者删除。栈是一种特殊的列表,栈内的元素只能通过列表的一端访问,成为栈顶。栈具有后进先出的特点,所以任何不在栈顶的元素都无法访问。
后进先出(LIFO,last-in-first-out)的数据结构。
对栈的操作
1.对栈的两种主要操作为将一个元素压入栈和将一个元素弹出栈。
入栈:push();
出栈:pop();
2.预览栈顶的元素peek();
pop()虽然可以访问栈顶元素,但调用后,栈顶元素也从栈中永久性的被删除。peek()方法只返回栈顶元素,并不删除它。
对栈的实现
定义stack类的构造函数:
functionStack(){
this.dataStore=[];//数组dataStore保存栈内元素,初始化为空数组
this.top=0;
//top为栈顶位置,被构造函数初始化为0,表示栈顶对应数组的起始位置0
this.push=push;
this.pop=pop;
this.peek=peek;
}
实现push()方法:
functionpush(element){
this.dataStore[this.top++]=element;
}
实现pop()方法:
functionpop(element){
returnthis.dataStore[--this.top];
//pop方法与push方法相反,它返回栈顶元素,同时将变量top的值减1
}
实现peek()方法:
functionpeek(element){
returnthis.dataStore[this.top-1];
//peek方法返回数组的第top-1个位置的元素,即栈顶元素。
}
如果对一个空栈调用peek()方法,结果为undefined,因为栈是空的,栈顶没有任何元素。
实现length():
需要知道栈内存储了多少元素,length()方法通过返回变量top值得方法返回栈内的元素个数。
functionlength(){
returnthis.top();
}
实现clear():
clear()将变量top的值设置为0,清空一个栈:
functionclear(){
this.top=0;
}
总结:Stack类
functionstack(){
this.dataStore=[];
this.top=0;
this.push=push;
this.pop=pop;
this.peek=peek;
this.clear=clear;
this.length=length;
}
functionpush(element){
this.dataStore[this.top++]=element;
}
functionpeek(){
returnthis.dataStore[this.top-1];
}
functionpop(){
returnthis.dataStore[--this.top];
}
functionclear(){
this.top=0;
}
functionlength(){
returnthis.top;
}
二、队列
队列是一种列表,队列智能在队尾插入元素,在队首删除元素。队列用于存储按顺序排列的数据,先进先出。
对队列的操作
队列主要两种操作,入队和出队,入队是在队尾插入新元素,出队是删除队首的元素。另一种是读取队头的元素,peek();
push()在数组末尾添加元素
names=[];
names.push("hling");
names.push("aling");
print(names);//显示hling,aling
shift()删除数组中第一个元素
names.shift(); print(names);//显示aling
定义Queue
functionQueue(){
this.dataStore=[];
this.enqueue=enqueue;
this.dequeue=dequeue;
this.front=front;
this.back=back;
this.toString=toString;
this.empty=empty;
}
enqueue()向队尾添加一个元素
functionenqueue(element){
this.dataStore.push(element);
}
dequeue()向队尾添加一个元素
functiondequeue(element){
returnthis.dataStore.shift(element);
}
读取队首和队尾的元素
functionfront(){
returnthis.dataStore[0];
}
functionback(){
returnthis.dataStore[this.dataStore.length-1];
}
toString()显示队列内的所有元素
functiontoString(){
varretStr="";
for(vari=0;i
empty()方法盘对队列是否为空
functionempty(){
if(this.dataStore.length==0){
returntrue;
}else{
returnfalse;
}
}
**Queue队列的类
functionQueue(){
this.dataStore=[];
this.enqueue=enqueue;
this.dequeue=dequeue;
this.front=front;
this.back=back;
this.toString=toString;
this.empty=empty;
}
functionenqueue(element){
this.dataStore.push(element);
}
functiondequeue(element){
returnthis.dataStore.shift(element);
}
functionfront(){
returnthis.dataStore[0];
}
functionback(){
returnthis.dataStore[this.dataStore.length-1];
}
functiontoString(){
varretStr="";
for(vari=0;i
更多关于JavaScript相关内容感兴趣的读者可查看本站专题:《JavaScript数据结构与算法技巧总结》、《JavaScript数学运算用法总结》、《JavaScript排序算法总结》、《JavaScript遍历算法与技巧总结》、《JavaScript查找算法技巧总结》及《JavaScript错误与调试技巧总结》
希望本文所述对大家JavaScript程序设计有所帮助。