1. 程式人生 > >js 實現棧和佇列

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)