栈及其应用:
es5封装一个简单的栈(数组篇)
function Stack () {
this.items = []
}
Stack.prototype.push = function (element) {
this.items.push(element)
}
Stack.prototype.pop = function () {
return this.items.pop()
}
Stack.prototype.peek = function () {
return this.items[this.items.length - 1]
}
Stack.prototype.isEmpty = function () {
return this.items.length === 0
}
Stack.prototype.size = function () {
return this.items.length
}
Stack.prototype.toString = function () {
return this.items.join()
}
应用这个栈空间
function decTobin (decNum) {
let stack = new Stack()
while (decNum > 0) {
stack.push(decNum % 2)
decNum = Math.floor(decNum / 2)
}
let binStr = ''
while (!stack.isEmpty()) {
binStr += stack.pop()
}
return binStr
}
es6封装一个栈(对象篇)
class Stack {
constructor() {
this.count = 0;
this.items = {};
}
push(element) {
this.items[this.count] = element;
this.count++;
}
size() {
return this.count;
}
isEmpty() {
return this.count === 0;
}
pop() {
if (this.isEmpty()) {
return undefined
}
this.count--
const res = this.items[this.count]
delete this.items[this.count]
return res
}
peek() {
if (this.isEmpty()) {
return undefined
}
return this.items[this.count - 1]
}
clear() {
this.count = 0
this.items = {}
}
toString() {
if (this.isEmpty()) {
return ''
}
let objString = `${this.items[0]}`
for (let i = 1; i < this.count; i++) {
objString = `${objString}, ${this.items[this.count]}`
}
return objString
}
}
es6 封装一个栈(数组篇)
class stackArray {
constructor() {
this.items = []
}
push(element) {
this.items.push(element)
}
pop() {
return this.items.pop()
}
peek() {
return this.items[this.items.length - 1]
}
isEmpty() {
return this.items.length === 0
}
size() {
return this.items.length
}
clear() {
this.items = []
}
}