1.首先,什麼是棧?
棧是一種線性邏輯結構
。只支持入棧和出棧操作,遵循後進先出
的原則(FILO)。
2.js描述棧
/*棧需要的操作:
* 1.入棧 push()
* 2.出棧 pop():該方法將棧頂元素永久刪除
* 3.預覽棧頂元素 peek():該方法只是返回棧頂元素,不會刪除棧頂元素。
* 4.記錄棧頂位置的變量 top:(1)當元素入棧時,該變量增大;(2)元素出棧時,該變量減小。
* 5.清空棧的方法 clear()
* 6.表示棧中元素個數的變量length
* 7.查看棧是否爲空的方法 isEmpty()
*
* 棧的實現:
* js中我們採用了數組來模擬棧結構的實現。
*/
// 棧類
function Stack() {
this.dataSource = [];
this.top = 0;
this.length = length;
this.push = push;
this.pop = pop;
this.peek = peek;
this.clear = clear;
this.isEmpty = isEmpty;
}
function push(data) {
this.dataSource[this.top++] = data;
}
function pop() { // 去元素的時候,從棧頂去元素,這裏從數組的最後一位去取元素
return this.dataSource[--this.top] ;
}
function clear() {
// 這裏將top值設置爲0,即可清空棧中元素了。因爲棧中元素的獲取是從top變量而來的。
this.top = 0;
}
function peek() {
// 因爲top始終指向的是,棧中下一個空位置,所以,減一
return this.dataSource[this.top - 1];
}
function length() {
return this.top;
}
function isEmpty() {
return !!this.top;
}
const s = new Stack();
3.棧的應用
- 進制轉換
- 迴文判斷
- 括號匹配
/*
*棧的應用:
*1.進制轉換
*2.判斷字符串是否爲迴文
* 3.括號匹配
*/
// 1.進制轉換
function mulBase(data, base) {
const s = new Stack();
do{ // 這裏處理了data爲0的情況
s.push( String(data % base) );
data = Math.floor(data / base);
} while(data > 0);
let converted = '';
do {
converted += s.pop();
} while (s.top > 0);
return converted;
}
// 2.判斷迴文
// 爲什麼可以用棧呢?因爲迴文的判斷就是正向和反向是否一致就行,而棧的存取方式正好合適
function isPalindrome(data) {
const stringData = String(data),
s = new Stack();
[...stringData].forEach(ele => {
s.push(ele);
});
return [...stringData].every(ele => ele === s.pop());
}
// 3.括號匹配
// 算術表達式: 12.3 + 23 / 12 + (3.14 * 14 返回括號缺失的位置
function parenthesesMatching(data) {
const stringData = String(data);
const s = new Stack();
for (let i = 0;i < stringData.length;i++) {
const str = stringData.charAt(i);
if (str === '(') { // 左括號
s.push(str);
}
if (str === ')') { // 遇到右括號,則棧頂元素,出棧
if(s.pop() !== '(') return false; // 出棧的元素,如果不是左括號,則false啦
}
}
return s.length() === 0;
}