js 实现栈和队列
js實(shí)現(xiàn)棧或者隊列有兩種方式:
1.數(shù)組:數(shù)組本身提供棧方法(push,pop),隊列方法(push,shift)。
代碼實(shí)現(xiàn)(棧):
/*=======棧結(jié)構(gòu)=======*/ var stack=function(){this.data=[]this.push=pushthis.pop=popthis.clear=clearthis.length=length } var push=function(element){this.data.push(element) } var pop=function(){this.data.pop() } var clear=function(){this.data.length=0 } var length=function(){return this.data.length; } //測試 var s=new stack() s.push('first') s.push('second') console.log(s) s.pop() console.log(s) // s.clear() console.log(s)代碼實(shí)現(xiàn)(隊列):
/*=======隊列結(jié)構(gòu)=======*/ var queue=function(){this.data=[]this.enQueue=enQueuethis.deQueue=deQueuethis.clear=clearthis.length=length } var enQueue=function(element){this.data.push(element) } var deQueue=function(){this.data.shift() } var clear=function(){this.data.length=0 } var length=function(){return this.data.length; } //測試 var q=new queue() q.enQueue('first') q.enQueue('second') console.log(q) q.deQueue() console.log(q) q.clear() console.log(q)?
2.鏈表:構(gòu)造鏈表結(jié)構(gòu),說白了就是鏈表的插入(尾插),移除(棧:末尾節(jié)點(diǎn)移除,隊列:頭結(jié)點(diǎn)移除)
代碼實(shí)現(xiàn)(棧):
/*=====棧結(jié)構(gòu)========*/ var node=function(data){this.data=datathis.next=null } var stack=function(){this.top=new node("top")this.push=pushthis.pop=popthis.clear=clearthis.length=length }/*=======入棧=======*/ var push=function(data){let newNode=new node(data)newNode.next=this.topthis.top=newNode } /*=======出棧=======*/ var pop=function(){let curr=this.topthis.top=this.top.nextcurr.next=null } /*=======清空棧=======*/ var clear=function(){this.top=new node('top') } /*=======棧長度=======*/ var length=function(){let cnt=0while(this.top.data!=='top'){this.top=this.top.nextcnt++}return cnt} /*=======測試=======*/ var s=new stack() s.push('first') s.push('second') console.log(s) s.pop() console.log(s) // s.clear() console.log(s.length())代碼實(shí)現(xiàn)(隊列):
/*=====隊列結(jié)構(gòu)========*/ var node=function(data){this.data=datathis.next=null } var queue=function(){this.top=new node("top")this.enQueue=enQueuethis.deQueue=deQueue }/*=======入隊=======*/ var enQueue=function(data){let newNode=new node(data)newNode.next=this.topthis.top=newNode } /*=======出隊=======*/ var deQueue=function(){let curr=this.topwhile(curr.next.next!==null && curr.next.next.data!=='top'){curr=curr.next}if(curr.next.next.data==='top'){curr.next=curr.next.next} }/*=======測試=======*/ var q=new queue() q.enQueue('first') q.enQueue('second') console.log(q) q.deQueue() console.log(q)?
轉(zhuǎn)載于:https://www.cnblogs.com/xingguozhiming/p/9906752.html
總結(jié)
- 上一篇: CSAPP:第三章程序的机器级表示1
- 下一篇: jmeter的性能监控框架搭建记录(In