栈后进先出
常用的方法
push()、pop()、peek()返回栈顶元素、isEmpty()、clear()、size()
栈的代码实现
function FStack(){
let items = [];
// 添加栈顶元素
this.push = function(element) {
items.push(element);
}
// 清除栈顶元素
this.pop = function(element) {
return items.pop();
}
// 返回栈顶元素
this.peek = function (){
return items[items.length - 1];
}
// 检查栈是否为空
this.isEmpty = function (){
return items.length == 0;
}
// 清空栈
this.clear = function(){
items = [];
}
// 查看栈的长度
this.size = function(){
return items.length;
}
// 输出栈内元素
this.print = function(){
console.log(items.toString());
}
}
用es6的weekmap实现栈
/ es6用类创建栈
let Stack = (function() {
const items = new WeakMap();
class CStack {
constructor () {
items.set(this, []);
}
push(element) {
let s = items.get(this);
s.push(element);
}
pop() {
let s = items.get(this);
let r = s.pop();
return r ;
}
peek() {
let s = items.get(this);
return s[s.length - 1];
}
isEmpty() {
let s = items.get(this);
return s.length == 0;
}
clear() {
let s = items.get(this);
s = [];
}
size() {
let s = items.get(this);
return s.length;
}
}
})();
例子用栈解决进制之间的转化问题
//十进制转化为任意进制
function baseConverter(decNumber,base) {
var remStack = new CStack(),
rem,
baseString = '',
digis = '0123456789ABCDEF';
while(decNumber > 0) {
rem = Math.floor(decNumber % base);
remStack.push(rem);
decNumber = Math.floor(decNumber/base);
}
while(!remStack.isEmpty()) {
baseString += digis[remStack.pop()];
}
return baseString;
}