搜索
首页web前端js教程js栈、队列、链表数据结构的实现代码分享

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

Feb 26, 2018 pm 03:17 PM
javascript分享数据结构

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

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不甚了解,等以后以后以后~~~

补充,优先队列

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

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<items.length;i++){            if(queueElement.priority<isFinite([i].priority)){
                items.splice(i,0,queueElement);
                added=true;                break;
            }
        }        if(!added){
            items.push(queueElement);
        }
    };    this.print=function(){
        return items;
    }
}var  pq=new PriorityQueue();
pq.enqueue(&#39;aa&#39;,2);
pq.enqueue(&#39;aba&#39;,4);
pq.enqueue(&#39;jjjj&#39;,8);
pq.enqueue(&#39;aaaaaaa&#39;,8);
pq.enqueue(&#39;aa&#39;,-1);
console.log(pq.print());

这里写图片描述

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(&#39;aa&#39;,2);
pq.enqueue(&#39;aba&#39;,4);
pq.enqueue(&#39;jjjj&#39;,8);
pq.enqueue(&#39;aaaaaaa&#39;,8);
pq.enqueue(&#39;aa&#39;,-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++<index){
                    previous=current;
                    current=current.next
                }
                node.next=current;
                previous.next=node;
            }
            length++;            // return 
        }else{
            alert("参数错误");
        }
    }    this.deleteAt=function(index){
        //从特定位置移除一个元素,index索引
        if(index>=0 && index<length){            var previousNode=null;            var node=head;            var position=0;            if(index==0){
                head=node.next;                return node.element;
            }else{                // console.log(node);
                while(position++<index){                    // console.log(node);
                    previousNode=node;
                    node=node.next;
                }
                previousNode.next=node.next;                return node.element;
            }
        }else{
            alert("参数不正确!");            return null;
        }

        length--;
    }    this.size=function(){
        return list.length;
    }    this.print=function(){
        var result=[];        for(let i = 0, length1 = list.length; i < length1; i++){
            result[i]=list[i];
        }        return result;
    }
}
var  linkList=new LinkList();
linkList.append(&#39;lorry1&#39;);
linkList.append(&#39;lorry2&#39;);
linkList.append(&#39;lorry3&#39;);
linkList.appendAt(&#39;lorry4&#39;,0);

linkList.appendAt(&#39;lorry5&#39;,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=&#39;&#39;;        var i=0;        while(current){
            str+=current.element+&#39; &#39;;
            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(&#39;lorry1&#39;);
linkList.append(&#39;lorry2&#39;);
linkList.append(&#39;lorry3&#39;);
linkList.appendAt(&#39;lorry4&#39;,0);
linkList.appendAt(&#39;lorry5&#39;,1);

linkList.appendAt(&#39;lorry5&#39;,0);console.log(&#39;我删除了...&#39;+linkList.deleteAt(1));console.log(&#39;头元素下一个元素是...&#39;+linkList.getHead().next.element);console.log(&#39;删除后链表内容...&#39;+linkList.toString());console.log(&#39;lorry5在链表中的位置...&#39;+linkList.indexOf(&#39;lorry5&#39;));console.log(&#39;lorriy5在链表中的位置....&#39;+linkList.indexOf(&#39;lorriy5&#39;));console.log(&#39;链表长度...&#39;+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线性表的入栈与出栈详解

以上是js栈、队列、链表数据结构的实现代码分享的详细内容。更多信息请关注PHP中文网其他相关文章!

声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
C和JavaScript:连接解释C和JavaScript:连接解释Apr 23, 2025 am 12:07 AM

C 和JavaScript通过WebAssembly实现互操作性。1)C 代码编译成WebAssembly模块,引入到JavaScript环境中,增强计算能力。2)在游戏开发中,C 处理物理引擎和图形渲染,JavaScript负责游戏逻辑和用户界面。

从网站到应用程序:JavaScript的不同应用从网站到应用程序:JavaScript的不同应用Apr 22, 2025 am 12:02 AM

JavaScript在网站、移动应用、桌面应用和服务器端编程中均有广泛应用。1)在网站开发中,JavaScript与HTML、CSS一起操作DOM,实现动态效果,并支持如jQuery、React等框架。2)通过ReactNative和Ionic,JavaScript用于开发跨平台移动应用。3)Electron框架使JavaScript能构建桌面应用。4)Node.js让JavaScript在服务器端运行,支持高并发请求。

Python vs. JavaScript:比较用例和应用程序Python vs. JavaScript:比较用例和应用程序Apr 21, 2025 am 12:01 AM

Python更适合数据科学和自动化,JavaScript更适合前端和全栈开发。1.Python在数据科学和机器学习中表现出色,使用NumPy、Pandas等库进行数据处理和建模。2.Python在自动化和脚本编写方面简洁高效。3.JavaScript在前端开发中不可或缺,用于构建动态网页和单页面应用。4.JavaScript通过Node.js在后端开发中发挥作用,支持全栈开发。

C/C在JavaScript口译员和编译器中的作用C/C在JavaScript口译员和编译器中的作用Apr 20, 2025 am 12:01 AM

C和C 在JavaScript引擎中扮演了至关重要的角色,主要用于实现解释器和JIT编译器。 1)C 用于解析JavaScript源码并生成抽象语法树。 2)C 负责生成和执行字节码。 3)C 实现JIT编译器,在运行时优化和编译热点代码,显着提高JavaScript的执行效率。

JavaScript在行动中:现实世界中的示例和项目JavaScript在行动中:现实世界中的示例和项目Apr 19, 2025 am 12:13 AM

JavaScript在现实世界中的应用包括前端和后端开发。1)通过构建TODO列表应用展示前端应用,涉及DOM操作和事件处理。2)通过Node.js和Express构建RESTfulAPI展示后端应用。

JavaScript和Web:核心功能和用例JavaScript和Web:核心功能和用例Apr 18, 2025 am 12:19 AM

JavaScript在Web开发中的主要用途包括客户端交互、表单验证和异步通信。1)通过DOM操作实现动态内容更新和用户交互;2)在用户提交数据前进行客户端验证,提高用户体验;3)通过AJAX技术实现与服务器的无刷新通信。

了解JavaScript引擎:实施详细信息了解JavaScript引擎:实施详细信息Apr 17, 2025 am 12:05 AM

理解JavaScript引擎内部工作原理对开发者重要,因为它能帮助编写更高效的代码并理解性能瓶颈和优化策略。1)引擎的工作流程包括解析、编译和执行三个阶段;2)执行过程中,引擎会进行动态优化,如内联缓存和隐藏类;3)最佳实践包括避免全局变量、优化循环、使用const和let,以及避免过度使用闭包。

Python vs. JavaScript:学习曲线和易用性Python vs. JavaScript:学习曲线和易用性Apr 16, 2025 am 12:12 AM

Python更适合初学者,学习曲线平缓,语法简洁;JavaScript适合前端开发,学习曲线较陡,语法灵活。1.Python语法直观,适用于数据科学和后端开发。2.JavaScript灵活,广泛用于前端和服务器端编程。

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热工具

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用

安全考试浏览器

安全考试浏览器

Safe Exam Browser是一个安全的浏览器环境,用于安全地进行在线考试。该软件将任何计算机变成一个安全的工作站。它控制对任何实用工具的访问,并防止学生使用未经授权的资源。

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器

适用于 Eclipse 的 SAP NetWeaver 服务器适配器

适用于 Eclipse 的 SAP NetWeaver 服务器适配器

将Eclipse与SAP NetWeaver应用服务器集成。

SublimeText3 Linux新版

SublimeText3 Linux新版

SublimeText3 Linux最新版