平时我们在学习文档和资料的时候,看到的大都是一些静态类型的语言(Java、c#)实现的数据结构和算法。对于前端小伙伴来说不是太友好,今天特意学习了一下用JavaScriot语言实现的数据结构-栈结构。
1.首先看一下复杂度为O(n),实现的栈结构
/**
* push() 添加一个新元素到栈顶
* pop() 移除栈顶的元素
* peek() 返回栈顶元素
* iSEmpty() 如果栈里没有任何元素就返回true,否则返回false
* clear() 移除栈里的所有元素
* size() 返回栈里的元素个数
*/
class Stack {
constructor() {
this.items = []
}
push(element) {
this.items.push(element)
}
pop() {
return this.items.pop()
}
peek() {
return this.items[this.items.length - 1]
}
isEmpaty() {
return this.items.length === 0
}
clear() {
this.items = [];
}
size() {
return this.items.length
}
toString(){
return this.items.toString()
}
}
const stack = new Stack()
console.log(stack.isEmpaty())
stack.push(1)
stack.push(2)
stack.push(3)
console.log(stack.toString())
stack.pop()
console.log(stack.toString())
console.log(stack.peek())
console.log(stack.isEmpaty())
console.log(stack.size())
stack.clear()
console.log(stack.toString())
2.我们再用对象实现一边,负责度为O(1)的栈结构
/**
* push() 添加一个新元素到栈顶
* pop() 移除栈顶的元素
* peek() 返回栈顶元素
* iSEmpty() 如果栈里没有任何元素就返回true,否则返回false
* clear() 移除栈里的所有元素
* size() 返回栈里的元素个数
* toString() 返回栈内的每一个元素
*/
class Stack {
constructor() {
this.count = 0;
this.items = {}
}
push(element) {
this.items[this.count] = element;
this.count++
}
pop() {
if (this.isEmpty()) {
return undefined
}
this.count--
const result = this.items[this.count]
delete this.items[this.count]
return result
}
peek() {
if (this.isEmpty()) {
return undefined
}
return this.items[--this.count]
}
size() {
return this.count
}
isEmpty() {
return this.count === 0
}
clear() {
this.count = 0;
this.items = {}
}
// toString() {
// if (this.isEmpty()) {
// return ''
// }
// let objString = ''
// for (let i = 0; i < this.count; i++) {
// objString += `${this.items[i]},`
// }
// return objString.slice(0, -1)
// }
toString() {
if (this.isEmpty()) {
return ''
}
let objString = `${this.items[0]}`
for (let i = 1; i < this.count; i++) {
objString = `${objString},${this.items[i]}`
}
return objString
}
}
const stack = new Stack()
console.log(stack.isEmpty())
console.log(stack.toString())
stack.push(5)
stack.push(8)
console.log(stack.toString())
stack.pop()
console.log(stack.toString())
3. 基于栈结构我们来解决一个实际问题 实现十进制到二进制的转化
/**
* 基于栈的思想解决一个十进制到二进制转化的问题
*/
function decimalToBinary(decNumber) {
const remStack = new Stack()
let number = decNumber
let rem
let binaryString = ''
while (number > 0) {
rem = Math.floor(number % 2)
remStack.push(rem)
number = Math.floor(number / 2)
}
while (!remStack.isEmpty()) {
binaryString += remStack.pop().toString()
}
return binaryString
}