栈,又叫堆栈,是和列表类似的一种数据结构,但是却更高效,因为栈内的元素只能通过列表的一端访问,称为栈顶,数据只能在栈顶添加或删除,遵循 先入后出(LIFO,last-in-first-out) 的原则,普遍运用于计算机的方方面面。
对栈的操作主要有两种,一是将一个元素压入栈,push方法,另一个就是将栈顶元素出栈,pop方法。
除此之外,栈还有其他的一些属性和方法:查看当前栈顶的元素值,我们使用 peek 方法,它仅仅返回栈顶元素值,并不删除它;clear 方法用于清空当前栈内的所有元素;top属性记录当前栈顶位置;length方法返回当前栈内元素总数等;接着我们定义栈的数据类型,并利用JS中的数组去实现它。
栈的实现
function Stack() {
this.dataStore = []; //初始化为空
this.top = 0; //记录栈顶位置
this.pop = pop; //出栈
this.push = push; //入栈
this.peek = peek; //查找栈顶元素
this.length = length; //查看栈内元素总数
this.clear = clear; //清空栈
}
function push(element){
this.dataStore[this.top++]=element;
}
function pop(){
return this.dataStore[--this.top];
}
function peek(){
if(this.top>0)return this.dataStore[this.top-1];
else return 'Empty';
}
function length(){
return this.top;
}
function clear(){
this.dataStore=[];
this.top=0;
}
案例
1.实现数制间的相互转换
function baseConverter(num, base) {
let s = new Stack();
while (num > 0) {
s.push(Math.floor(num % base));
num = Math.floor(num / base);
}
let res = '';
while (s.length() > 0) {
res += s.pop();
}
return res;
}
2.判断一个字符串是不是回文
function isPalindrome(str) {
let s = new Stack();
for (let i = 0; i < str.length; i++) {
s.push(str[i]);
}
let reverseStr = '';
while (s.length() > 0) {
reverseStr += s.pop();
}
if (str === reverseStr) return true;
else return false;
}