分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > 软件开发

js 实现栈和队列

发布时间:2023-09-06 02:21责任编辑:苏小强关键词:js

js实现栈或者队列有两种方式:

1.数组:数组本身提供栈方法(push,pop),队列方法(push,shift)。

代码实现(栈):

/*=======栈结构=======*/var stack=function(){ ???this.data=[] ???this.push=push ???this.pop=pop ???this.clear=clear ???this.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)

代码实现(队列):

/*=======队列结构=======*/var queue=function(){ ???this.data=[] ???this.enQueue=enQueue ???this.deQueue=deQueue ???this.clear=clear ???this.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.链表:构造链表结构,说白了就是链表的插入(尾插),移除(栈:末尾节点移除,队列:头结点移除)

代码实现(栈):

/*=====栈结构========*/var node=function(data){ ???this.data=data ???this.next=null}var stack=function(){ ???this.top=new node("top") ???this.push=push ???this.pop=pop ???this.clear=clear ???this.length=length}/*=======入栈=======*/var push=function(data){ ???let newNode=new node(data) ???newNode.next=this.top ???this.top=newNode}/*=======出栈=======*/var pop=function(){ ???let curr=this.top ???this.top=this.top.next ???curr.next=null}/*=======清空栈=======*/var clear=function(){ ???this.top=new node(‘top‘)}/*=======栈长度=======*/var length=function(){ ???let cnt=0 ???while(this.top.data!==‘top‘){ ???????this.top=this.top.next ???????cnt++ ???} ???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())

代码实现(队列):

/*=====队列结构========*/var node=function(data){ ???this.data=data ???this.next=null}var queue=function(){ ???this.top=new node("top") ???this.enQueue=enQueue ???this.deQueue=deQueue}/*=======入队=======*/var enQueue=function(data){ ???let newNode=new node(data) ???newNode.next=this.top ???this.top=newNode}/*=======出队=======*/var deQueue=function(){ ???let curr=this.top ???while(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)

js 实现栈和队列

原文地址:https://www.cnblogs.com/xingguozhiming/p/9906752.html

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved