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)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM