github博客地址
棧(stack)又名堆棧,它是一種運算受限的線性表。遵循后進先出原則,像垃圾桶似的。
功能實現依然按照增刪改查來進行,內部數據存儲可以借用語言原生支持的數組。
棧類
function Stack(){this.data = [];
}
添加數據
數據添加到末尾
push: function (element){this.data.push(element);
}
刪除數據
從末尾刪除
pop: function (){this.data.pop();
}
獲取數據
返回最后一個添加的
peek: function (){return this.data[this.size() - 1];
}
是否為空
isEmpty: function (){return this.data.length == 0;
}
清空數據
clear: function (){this.data= [];
}
數據長度
size: function (){return this.data.length;
}
輔助函數,打印數據
print: function (){console.log(this.data.toString());
}
完整代碼


1 function Stack(){ 2 this.data = []; 3 } 4 Stack.prototype = { 5 push: function (element){ 6 this.data.push(element); 7 }, 8 pop: function (){ 9 this.data.pop(); 10 }, 11 peek: function (){ 12 return this.data[this.data.length - 1]; 13 }, 14 isEmpty: function (){ 15 return this.data.length == 0; 16 }, 17 clear: function (){ 18 this.data= []; 19 }, 20 size: function (){ 21 return this.data.length; 22 }, 23 print: function (){ 24 console.log(this.data.toString()); 25 } 26 }
?