栈是一种遵从后进先出(LIFO)原则的有序集合。
创建一个栈
它需要包含以下方法
- push(ele(s)) 添加一个或多个新元素到栈顶
- pop() 移除栈顶元素并返回
- peek() 返回栈顶元素
- isEmpty() 栈内有元素返回
false,没有返回true - clear() 移除栈内所有元素
- size() 返回栈内元素个数
class Stack {
constructor() {
this.items = [];
}
}
push
push(ele) {
this.items.push(ele);
}
pop
pop() {
return this.items.pop();
}
peek
peek() {
return this.items.at(-1);
}
isEmpty
isEmpty() {
return !this.items.length;
}
clear
clear() {
this.items = [];
}
size
size() {
return this.items.length;
}
完整代码
class Stack {
constructor() {
this.items = [];
}
push(ele) {
this.items.push(ele);
}
pop() {
return this.items.pop();
}
peek() {
return this.items.at(-1);
}
isEmpty() {
return !this.items.length;
}
clear() {
this.items = [];
}
size() {
return this.items.length;
}
}
应用:十进制转二进制
const decimalToBinary = (decNumber) => {
const stack = new Stack();
let num = decNumber;
let rem;
let binaryStr = '';
while(num > 0) {
rem = Math.floor(number % 2);
stack.push(rem);
num = Math.floor(number / 2)
}
while(!stack.isEmpty) {
binaryStr += stack.pop().toString();
}
return binaryStr;
}