js實現棧

js實現棧的基本操作

function Stack() {
    this.dataStore = [];
    this.top = 0;//棧頂
    this.push = push;//入棧
    this.pop = pop;//出棧
    this.isEmpty = isEmpty;//判斷是否爲空
    this.peek = peek;//取棧頂元素
    this.length = length;//棧的長度
    this.clear = clear;//棧的清空
}
function push(val) {
    this.dataStore[this.top++] = val;
}
function pop() {
    if (!this.isEmpty()) {
        this.top--;
        return this.dataStore.pop();
    } else {
        return null;
    }
}
function isEmpty() {
    return this.top === 0;
}
function peek() {
    if (!this.isEmpty()) {
        return this.dataStore[this.top - 1];
    } else {
        return null;
    }
}
function length() {
    return this.top;
}
function clear() {
    this.dataStore = [];
    this.top = 0;
}
var stk = new Stack();//調用
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章