0

0

js栈、队列、链表数据结构的实现代码分享

小云云

小云云

发布时间:2018-02-26 15:17:08

|

1763人浏览过

|

来源于php中文网

原创

数据结构有讲过,栈是一种遵从后进先出原则的有序集合,书中对栈的形容非常到位,就像是堆盘子,先放的肯定在下面的位置,最上面的是才放的。给栈内添加元素,最先添加的在栈底,最后一个加进去的称为栈顶元素。

js实现栈及其方法

具体内容有

  • 创建栈:在js里我们用数组类比栈

  • 向栈里添加元素push()

  • 移除元素  delete()

  • 栈大小  size()

  • 查看栈顶元素 peek()

  • 检查栈是否为空 isEmpty()

  • 清空栈  empty()

  • 打印栈 print()

  • 使用

代码

    function Stack(){
    var stack=[];    this.push=function(para){
        stack.push(para);
    };    this.delete=function(){
        // 删除栈顶元素
        stack.pop();//删除数组末尾元素,
    }    this.size=function(){
        return stack.length;
    }    this.peek=function(){
        return stack[stack.length-1];
    }    this.isEmpty=function(){
        if(stack.length==0){            return true;
        }else{            return false;
        }
    }    this.emptyStack=function(){
        stack=[];
    }    this.print=function(){
        return stack.toString();
    }
}

使用

var myStack=new Stack();
myStack.push(1);
myStack.push(4);
myStack.push(6);
console.log('删除前栈内元素'+myStack.print());
console.log('删除前栈顶元素'+myStack.peek());
console.log('删除前栈元素size'+myStack.size());
myStack.delete();
console.log('删除后栈内元素'+myStack.print());
console.log('删除后栈顶元素'+myStack.peek());
console.log('删除前栈元素size'+myStack.size());
console.log('栈是否为空'+myStack.isEmpty());
myStack.emptyStack();
console.log('清空栈,栈是否为空'+myStack.isEmpty());
console.log('清空栈,栈元素size'+myStack.size());

这里写图片描述

队列

先进先出,就像喝孟婆汤要排队一样,先来的排在前面,后面来的就排在队尾,要投胎肯定是前面喝完的人去,操作队列也一样,从队列前面移除元素,从队尾添加元素。和栈的实现大同小异

function Queue(){
    var queue=[];    this.push=function(para){
        queue.push(para);
    }    this.delete=function(){
        // 从队首移除,即删除的是数组第一位
        queue.shift();
    }    this.queueFront=function(){
        return queue[0];
    }    this.isEmpty=function(){
        if(queue.length==0){            return true;
        }else{            return false;
        }
    }    this.size=function(){
        return queue.length;
    }    this.emptyQueue=function(){
        queue=[];
    }    this.print=function(){
        return queue.toString();
    }
}var myQueue=new Queue();
myQueue.push(1);
myQueue.push(4);
myQueue.push(6);
console.log('删除前队列内元素'+myQueue.print());
console.log('删除前队列顶元素'+myQueue.queueFront());
console.log('删除前队列元素size'+myQueue.size());
myQueue.delete();
console.log('删除后队列内元素'+myQueue.print());
console.log('删除后队列顶元素'+myQueue.queueFront());
console.log('删除前队列元素size'+myQueue.size());
console.log('队列是否为空'+myQueue.isEmpty());
myQueue.emptyQueue();
console.log('清空队列,队列是否为空'+myQueue.isEmpty());
console.log('清空队列,队列元素size'+myQueue.size());

这里写图片描述

实现的不同点

删除操作和访问队首(栈顶)元素的方法不一样,这是由于后进先出和先进先出的原则不同造成的,栈删除的是数组最后一位( pop() ),队列删除数组的第一位(shift()),栈顶元素是数组最后一位,而队列的队首元素是数组第一位元素。

书上有用ES6的新特性写的实现方式,emmmm我ES6不甚了解,等以后以后以后~~~

补充,优先队列

说白了就是有特权,书中规定优先级小的在前面。然后自己实现了一下,代码和书中不太一样,两个都运行了一下
先贴一下书上的代码

ghiblitattoo
ghiblitattoo

用AI创造独特的吉卜力纹身

下载
function PriorityQueue(){
    let items=[];    function QueueElement(element,priority){
        this.element=element;        this.priority=priority;
    }    this.enqueue=function(element,priority){
        let queueElement=new QueueElement(element, priority);        let added=false;        for(let i=0;i

这里写图片描述

function PriorityQueue(){
    // 按优先级从小到大排列,
    var queue=[];    function QueueElement(ele,prior){
        this.element=ele;        this.prior=prior;
    }    this.enqueue=function(ele,prior){
        //循环遍历队列内所有元素,如果当前优先级小,则放在该位之前
        var curr=new QueueElement(ele, prior);        if(queue.length==0){
            queue.push(curr);
        }else{            if(curr.prior<=queue[0].prior){
                queue.splice(0,0,curr);
            }else{
                queue.push(curr);
            }
        }
    }    this.print=function(){
        return queue;
    }
}var  pq=new PriorityQueue();
pq.enqueue('aa',2);
pq.enqueue('aba',4);
pq.enqueue('jjjj',8);
pq.enqueue('aaaaaaa',8);
pq.enqueue('aa',-1);
console.log(pq.print());

这里写图片描述

嗷嗷嗷 截完图才发现最后应该输出element,不要优先级,这里补一下上面两个的print方法(注意,我声明的是queue,书中是items ^_^)

this.print=function(){
        var result=[];        for(let j = 0, length2 = items.length; j < length2; j++){
            result[j]=items[j].element;
        }
        return result;
    }

链表

链表存储有序的元素集合,但不同于数组的是,链表中的元素并不是连续放置的。每个元素由存储元素本身的节点和一个指向下一个元素的引用(指针)构成,

单链表

链表类的方法都有:

append(para) 在链表尾部添加元素appendAt(element,index) 在指定位置添加元素deleteAt(index) 删除指定位置的链表元素getHead() 获得链表头元素size() 获得链表大小print() 打印出链表内容 

toString() 输出链表元素的内容indexOf(para)  查找元素如果在链表中找到了就返回他的位置,没找到就返回-1isEmpty() 判断链表是否为空size()  获取链表长度

具体代码

因为是写一段测试一段,所以函数没在一起写,先分开后面再汇总。

function LinkList(){
    let Node=function(element){
        this.element=element;        this.next=null;
    };    var list=[];
    let length=0;
    let head=null;
    let currNode=null;    this.append=function(para){
        //链表尾部追加元素
        var node=new Node(para);        var current;//一直指向上一个添加的节点
        if(head==null){            //插入第一个元素
            head=node;
            currNode=head;            // console.log(head);

        }else{            //不是第一个元素
            //上一个的next指针指向当前node;
            currNode.next=node;            // console.log(currNode);
            currNode=node;
        }
        length++;        // list.push(node);
    }    this.getHead=function(){
        return head;
    }    this.appendAt=function(element,index){
        if(index>=0 && index<=length){            var node=new Node(element);            var current=head;            var previous;            var position=0;            if(index==0){
                node.next=current;
                head=node;
            }else{                while(position++=0 && index
var  linkList=new LinkList();
linkList.append('lorry1');
linkList.append('lorry2');
linkList.append('lorry3');
linkList.appendAt('lorry4',0);

linkList.appendAt('lorry5',0);// 那么当前链表的元素顺序是 lorry5,lorry4,lorry1,lorry2,lorry3console.log(linkList.deleteAt(2));
console.log(linkList.getHead().next);//获取头元素的下一个元素
控制台打印出来的内容:lorry1                       linkList.js:112 Node {element: "lorry4", next: Node}  linkList.js:115 
    element:"lorry4"
    next:Node {element: "lorry2", next: Node}
    __proto__:Object

这里写图片描述
toString,size,indexOf方法

this.toString=function(){
        var current=head;        var str='';        var i=0;        while(current){
            str+=current.element+' ';
            current=current.next;
        }        return str;
    }    this.indexOf=function(para){
        //返回首个出现该参数的位置
        var current=head;        var index=-1;        // var i=0;
        while(current){
            index+=1;            if(current.element==para){                return index;
            }
            current=current.next;
        }        return -1;
    }    this.isEmpty=function(){
        return length==0;
    }    this.size=function(){
        return length;
    }
var  linkList=new LinkList();
linkList.append('lorry1');
linkList.append('lorry2');
linkList.append('lorry3');
linkList.appendAt('lorry4',0);
linkList.appendAt('lorry5',1);

linkList.appendAt('lorry5',0);console.log('我删除了...'+linkList.deleteAt(1));console.log('头元素下一个元素是...'+linkList.getHead().next.element);console.log('删除后链表内容...'+linkList.toString());console.log('lorry5在链表中的位置...'+linkList.indexOf('lorry5'));console.log('lorriy5在链表中的位置....'+linkList.indexOf('lorriy5'));console.log('链表长度...'+linkList.size());
linkList.js:143 我删除了...lorry4linkList.js:145 头元素下一个元素是...lorry5linkList.js:146 删除后链表内容...lorry5 lorry5 lorry1 lorry2 lorry3 
linkList.js:147 lorry5在链表中的位置...0linkList.js:148 lorriy5在链表中的位置....-1linkList.js:150 链表长度...5

这里写图片描述

相关推荐:

PHP实现栈数据结构和括号匹配

PHP使用两个栈实现队列功能

php线性表的入栈与出栈详解

相关专题

更多
php文件怎么打开
php文件怎么打开

打开php文件步骤:1、选择文本编辑器;2、在选择的文本编辑器中,创建一个新的文件,并将其保存为.php文件;3、在创建的PHP文件中,编写PHP代码;4、要在本地计算机上运行PHP文件,需要设置一个服务器环境;5、安装服务器环境后,需要将PHP文件放入服务器目录中;6、一旦将PHP文件放入服务器目录中,就可以通过浏览器来运行它。

2816

2023.09.01

php怎么取出数组的前几个元素
php怎么取出数组的前几个元素

取出php数组的前几个元素的方法有使用array_slice()函数、使用array_splice()函数、使用循环遍历、使用array_slice()函数和array_values()函数等。本专题为大家提供php数组相关的文章、下载、课程内容,供大家免费下载体验。

1691

2023.10.11

php反序列化失败怎么办
php反序列化失败怎么办

php反序列化失败的解决办法检查序列化数据。检查类定义、检查错误日志、更新PHP版本和应用安全措施等。本专题为大家提供php反序列化相关的文章、下载、课程内容,供大家免费下载体验。

1549

2023.10.11

php怎么连接mssql数据库
php怎么连接mssql数据库

连接方法:1、通过mssql_系列函数;2、通过sqlsrv_系列函数;3、通过odbc方式连接;4、通过PDO方式;5、通过COM方式连接。想了解php怎么连接mssql数据库的详细内容,可以访问下面的文章。

1036

2023.10.23

php连接mssql数据库的方法
php连接mssql数据库的方法

php连接mssql数据库的方法有使用PHP的MSSQL扩展、使用PDO等。想了解更多php连接mssql数据库相关内容,可以阅读本专题下面的文章。

1485

2023.10.23

html怎么上传
html怎么上传

html通过使用HTML表单、JavaScript和PHP上传。更多关于html的问题详细请看本专题下面的文章。php中文网欢迎大家前来学习。

1256

2023.11.03

PHP出现乱码怎么解决
PHP出现乱码怎么解决

PHP出现乱码可以通过修改PHP文件头部的字符编码设置、检查PHP文件的编码格式、检查数据库连接设置和检查HTML页面的字符编码设置来解决。更多关于php乱码的问题详情请看本专题下面的文章。php中文网欢迎大家前来学习。

1589

2023.11.09

php文件怎么在手机上打开
php文件怎么在手机上打开

php文件在手机上打开需要在手机上搭建一个能够运行php的服务器环境,并将php文件上传到服务器上。再在手机上的浏览器中输入服务器的IP地址或域名,加上php文件的路径,即可打开php文件并查看其内容。更多关于php相关问题,详情请看本专题下面的文章。php中文网欢迎大家前来学习。

1307

2023.11.13

c++空格相关教程合集
c++空格相关教程合集

本专题整合了c++空格相关教程,阅读专题下面的文章了解更多详细内容。

0

2026.01.23

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
React 教程
React 教程

共58课时 | 4万人学习

TypeScript 教程
TypeScript 教程

共19课时 | 2.4万人学习

Bootstrap 5教程
Bootstrap 5教程

共46课时 | 3万人学习

关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号