// 在JavaScript裏面,已經擁有push ,pop,shift,unshift的功能,雖然棧和隊列不難,然而,直接用太過簡單。
1 // 隊列 2 function Queue() { 3 var arr = []; 4 var size = 0; 5 6 var push = function(num) { 7 arr[size] = num; 8 size++; 9 }; 10 var shift = function() { 11 var ret = arr[0]; 12 for (var i = size-1;i>0;i--){ 13 arr[i-1] = arr[i]; 14 } 15 size--; 16 arr.length = size; // arr[size] = null; 17 return ret; 18 }; 19 var peek = function() { 20 return arr[size-1]; 21 }; 22 23 var isEmpty = function() { 24 if(size === 0) { 25 return true; 26 } 27 return false; 28 }; 29 30 return { 31 shift: shift, 32 push: push, 33 peek: peek, 34 isEmpty: isEmpty 35 }; 36 }; 37 var qu = new Queue();
1 // 棧 2 function Stock(num) { 3 var arr = []; 4 var size = 0; 5 6 this.push = function(num) { 7 arr[size] = num; 8 size++; 9 } 10 this.pop = function() { 11 var ret = arr[--size]; 12 arr[size] = null; 13 return ret; 14 } 15 this.peek = function() { 16 return arr[size-1]; 17 }; 18 19 this.isEmpty = function() { 20 if(size === 0) { 21 return true; 22 } 23 return false; 24 }; 25 this.getSize = function() { 26 return size; 27 } 28 }; 29 var st = new Stock();