Home > Web Front-end > JS Tutorial > body text

Implementation code sharing of js stack, queue, and linked list data structures

小云云
Release: 2018-02-26 15:17:08
Original
1478 people have browsed it

Data structure has been mentioned before. The stack is an ordered collection that follows the last-in-first-out principle. The description of the stack in the book is very accurate. It is like a pile of plates. The first thing must be placed at the bottom. position, the top one is placed. When adding elements to the stack, the first element added is at the bottom of the stack, and the last element added is called the top element.

js implements stack and its methods

The specific content is

  • Creating a stack: In js we use an array analogy to a stack

  • Add elements to the stack push()

  • Remove elements delete()

  • Stack size size()

  • View the top element of the stack peek()

  • Check whether the stack is empty isEmpty()

  • Empty the stack empty()

  • Print stack print()

  • Use

Code

    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();
    }
}
Copy after login

Use

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());
Copy after login

Implementation code sharing of js stack, queue, and linked list data structures

Queue

First in, first out, just like queuing up to drink Meng Po soup, those who come first will be in front. Those who come later will be at the end of the queue. If they want to be reincarnated, the person who finished drinking in front must go. The same is true for the operation queue. Elements are removed from the front of the queue and elements are added from the end of the queue. It is similar to the implementation of stack

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());
Copy after login

Implementation code sharing of js stack, queue, and linked list data structures

The difference in implementation

The method of deletion operation and accessing the head (top of stack) element is different. This is because This is caused by the different principles of last-in-first-out and first-in-first-out. The stack deletes the last bit of the array (pop()), while the queue deletes the first bit of the array (shift()). The top element of the stack is the last bit of the array, while The first element of the queue is the first element of the array.

The book uses the implementation method written with the new features of ES6. Emmmm, I don’t know much about ES6. I will wait for it in the future~~~

I will add it, priority queue

To put it bluntly There are privileges, and the book stipulates that those with lower priority are at the front. Then I implemented it myself. The code was different from the one in the book. I ran both.
First post the code in the book

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());
Copy after login

Implementation code sharing of js stack, queue, and linked list data structures

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());
Copy after login

Implementation code sharing of js stack, queue, and linked list data structures

After taking the screenshot, I realized that element should be output at the end, without priority. Here are the print methods of the above two (note that I declared queue, in the book it is items ^_^)

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

Linked list

A linked list stores an ordered collection of elements, but unlike an array, the elements in a linked list are not placed continuously. Each element consists of a node that stores the element itself and a reference (pointer) pointing to the next element.

Singly linked list

The methods of the linked list class have:

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

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

Specific code

Because we are writing one test section and one section, the functions are not written together. We separate them first and then summarize them later.

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;
    }
}
Copy after login
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);//获取头元素的下一个元素
Copy after login
控制台打印出来的内容:lorry1                       linkList.js:112 Node {element: "lorry4", next: Node}  linkList.js:115 
    element:"lorry4"
    next:Node {element: "lorry2", next: Node}
    __proto__:Object
Copy after login

Implementation code sharing of js stack, queue, and linked list data structures
toString, size, indexOf method

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;
    }
Copy after login
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());
Copy after login
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
Copy after login

Implementation code sharing of js stack, queue, and linked list data structures

##Related recommendations:

PHP implements stack data structure and bracket matching

PHP uses two stacks to implement the queue function

php Detailed explanation of the push and pop of linear tables

The above is the detailed content of Implementation code sharing of js stack, queue, and linked list data structures. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!