javascript 棧 Stack


棧是只允許在表尾進行插入,刪除的線性表。特點后進先出。

下面將演示用數組實現的棧

棧初始化:創建一個空棧

Init:function(){
   this.STACKMAX = 100;
   this.stack = new Array(this.STACKMACK);
   this.top = -1;
   return this.stack;
}

 

判斷棧空: 若棧為空返回true,否則返回false

Empty:function(){
   if(this.top==-1){
       return true;
   }
   else{
        return false;
   }
}

 

進棧:若棧滿,返回“棧滿”。否則將元素elem作為新的棧頂元素。

Push:function(elem){
   if(this.top==this.STACKMAX-1){
      return "棧滿";
   }
   else{
      this.top++;
      this.stack[this.top] = elem;
   }
 }

 

退棧:刪除棧頂元素,並返回其值

Pop:function(){
    if(this.top==-1){
        return "空棧,無法刪除棧頂元素!";
    }
    else{
        var x = this.stack[this.top];
        this.top--;
        return x;
    }
 }

 

讀棧頂元素:返回棧頂元素

Top:function(){
    if(this.top!=-1){
        return this.stack[this.top];
    }
    else{
        return "空棧,頂元素無返回值!";
     }
 }

 

清空棧:將棧清空為空棧

Clear:function(){
    this.top=-1;
}

 

棧長度:返回棧的元素個數,既棧的長度

Length:function(){
   return this.top+1;
}


棧示例代碼如下:

            var Stack = function(){}
            
            Stack.prototype={
                Init:function(){
                    this.STACKMAX = 100;
                    this.stack = new Array(this.STACKMACK);
                    this.top = -1;
                    return this.stack;
                },
                Empty:function(){
                    if(this.top==-1){
                        return true;
                    }
                    else{
                        return false;
                    }
                },
                Push:function(elem){
                    if(this.top==this.STACKMAX-1){
                        return "棧滿";
                    }
                    else{
                        this.top++;
                        this.stack[this.top] = elem;
                    }
                },
                Pop:function(){
                    if(this.top==-1){
                        return "空棧,無法刪除棧頂元素!";
                    }
                    else{
                        var x = this.stack[this.top];
                        this.top--;
                        return x;
                    }
                },
                Top:function(){
                    if(this.top!=-1){
                        return this.stack[this.top];
                    }
                    else{
                        return "空棧,頂元素無返回值!";
                    }
                },
                Clear:function(){
                    this.top=-1;
                },
                Length:function(){
                    return this.top+1;
                }
            }

 

在最近的日子里會給出棧的應用的例子,在此敬請期待。。。


免責聲明!

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



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