JavaScript数据结构 ——栈
JavaScript数据结构(一) 栈
什么是栈
栈是一种受限的线性结构,只允许在一端(栈顶
)进行删除(出栈
)和添加(入栈
)操作。
栈的特点
:先进后出,后进先出
练习:
有 6 个元素 6,5,4,3,2,1 按顺序进栈,问下列哪一个不是合法的出栈顺序。
- A:5 4 3 6 1 2 (√)
- B:4 5 3 2 1 6 (√)
- C:3 4 6 5 2 1 (×)
- D:2 3 4 1 5 6 (√)
解析:
已经压入栈的某个元素,在他之前压入栈的元素不能比它先出栈。
常见栈操作
push()
添加一个新元素到栈顶位置。pop()
移除栈顶的元素,同时返回被移除的元素。peek()
返回栈顶的元素,不对栈做任何修改(该方法不会移除栈顶的元素,仅仅返回它)。isEmpty()
如果栈里没有任何元素就返回true
,否则返回false
。size()
返回栈里的元素个数。这个方法和数组的length
属性类似。toString()
将栈结构的内容以字符串的形式返回。
JavaScript(数组)实现栈结构
function Stack1() {
this.stack = [];
Stack1.prototype.push = function(item) {
this.stack.push(item);
}
Stack1.prototype.pop = function() {
return this.stack.pop();
}
Stack1.prototype.peek = function() {
return this.stack[this.stack.length - 1];
}
Stack1.prototype.isEmpty = function() {
return this.stack.length == 0;
}
Stack1.prototype.size = function() {
return this.stack.length;
}
Stack1.prototype.toString = function() {
let result = '';
this.stack.forEach(value => {
result = result + value + " ";
});
return result;
}
}
//利用栈结构的特点封装实现十进制转换为二进制的方法。
function decToBit(num) {
var stack = new Stack1();
while (num > 0) {
stack.push(num % 2);
num = Math.floor(num / 2);
};
let result = '';
while (!stack.isEmpty()) {
result += stack.pop()
}
return result
}
console.log(decToBit(5));
console.log(decToBit(100));