第四章棧(1)
阿新 • • 發佈:2018-11-02
一、Stack()類
function Stack(){
this.dataStore=[];
this.top=0;
this.push=push;
this.pop=pop;
this.peek=peek;
this.clear=clear;
this.length=length;
this.isEmpty=isEmpty;
}
function push(element){
this.dataStore[this.top++]=element;
return this.top;
}
function pop(){
return this.dataStore[--this.top];
}
function peek(){
return this.dataStore[this.top-1];
}
function length(){
return this.top;
}
function clear(){
this.top=0;
}
function isEmpty(){
if(this.length()<=0){
return true;
}else{
return false;
}
}
//測試Stack類的實現
let s=new Stack();
s.push("Tom");
s.push("Jack");
s.push("Bryan");
console.log("length: " + s.length());//3
console.log(s.peek());//Bryan
let popped = s.pop();
console.log("The popped element is: " + popped);//Bryan
console.log(s.peek());//Jack
s.push("Cynthia");
console.log(s.peek());//Cynthia
s.clear();
console.log("length: " + s.length());//0
console.log(s.peek());//undefined
s.push("Clayton");
console.log(s.peek());//Clayton
二、棧的應用
1.數制間的相互轉換:假設想將數字n轉換為以b為基數的數字,實現轉換的演算法如下(1) 最高位為 n % b,將此位壓入棧
(2) 使用 n/b代替n
(3) 重複步驟1 和 2,直到 n 等於 0,且沒有餘數。
(4) 持續將棧內元素彈出,直到棧為空,依次將這些元素排列,就得到轉換後數字的字串形式
function mulBase(num,base){
let s=new Stack();
do{
s.push(num%base);
num=Math.floor(num /= base);
}while(num>0);
let converted="";
while(s.length()>0){
converted +=s.pop();
}
return converted;
}
let num=31;
let base=2;
let newNum=mulBase(num,base);
console.log(num+" converted to base "+base+" is "+newNum);//11111
num =125;
base=8;
newNum=mulBase(num,base);
console.log(num+" converted to base "+base+" is "+newNum);//175
2.判斷給定字串是否是迴文
function isPalindrome(word){
let s=new Stack();
for(let i=0;i<word.length;i++){
s.push(word[i]);
}
let rword="";
while(s.length()>0){
rword +=s.pop();
}
if(word==rword){
return true;
}else{
return false;
}
}
let word="hello";
if(isPalindrome(word)){
console.log(word+" is a palindrome");
}else{
console.log(word+"is not a palindrome");
}
word='racecar';
if(isPalindrome(word)){
console.log(word+" is a palindrome");
}else{
console.log(word+"is not a palindrome");
}
3.遞迴
function factorial(n){
if(n==0){
return 1;
}else{
return n*factorial(n-1);
}
}
function fact(n){
let s=new Stack();
while(n>1){
s.push(n--);
}
let product=1;
while(s.length()>0){
product *=s.pop();
}
return product;
}
console.log(factorial(6));//720
console.log(fact(6));//720
三、習題
1.棧可以用來判斷一個算術表示式中的括號是否匹配。編寫一個函式,該函式接受一個算術表示式作為引數,返回括號缺失的位置。下面是一個括號不匹配的算術表示式的例子:2.3 + 23 / 12 + (3.14159×0.24。
function signUp(stack,ele){
switch(ele){
case "{":
case "[":
case "(":
stack.push(ele);
break;
case "}":
case "]":
case ")":
let topEle=stack.pop();
console.log(stack.top);
if((topEle=='{'&& ele=='}')||(topEle=='['&& ele==']')||(topEle=='('&& ele==')')){
console.log('ok');
}else{
console.log("括號不匹配");
return;
}
break;
}
}
let stack=new Stack();
let str="2.3 + 23 / 12 + ( 3.14159 × 0.24 ";
str=str.split(" ");
for(let i=0;i<str.length;i++){
signUp(stack,str[i]);
}
if(!stack.isEmpty()){
console.log("括號不匹配");
}