「这是我参与2022首次更文挑战的第1天,活动详情查看:2022首次更文挑战」。
我个人觉得要想进大厂,就必须学习了解算法和数据结构,经历了多次面试之后,也知道了算法和数据结构的重要性,所以,我也打算从今天开始,进入学习,下载了一下电子书,边看书,边跟着书的例子来敲一下代码,下面就开始总结一下对算法和数据结构的学习吧。
第一天:开始了解栈
栈
栈是一种遵从后进先出(LIFO)原则的有序集合。新添加或待删除的元素都保存在栈的同一端,称作栈顶,另一端就叫栈底
栈有一个很重要的应用:在程序设计语言中实现了递归。比较经典的例子就是斐波那契数例。在现实生活中也能发现很多栈的例子。例如,一摞书或者餐厅里叠放的盘子先放下的,最后拿出来,都被压着
实现一套基于js对象的栈结构
需要有的方法
- push(element(s)):添加一个(或几个)新元素到栈顶。
- pop():移除栈顶到元素,同时返回被移除的元素。
- peek():返回栈顶的元素买不对栈做任何修改
- isEmpty():如果栈里没有任何元素就返回true,否则返回false
- clear():移除栈里面的所有元素
- size():返回栈里的元素个数。
创建栈
class Stack {
constructor() {
this.count = 0
this.items = {}
}
push(element) {
this.items[this.count] = element
this.count++
}
isEmpty() {
return this.count === 0
}
size() {
return this.count
}
peek() {
if (this.isEmpty()) {
return undefined
}
return this.items[this.count - 1]
}
pop() {
if (this.isEmpty()) {
return undefined
}
this.count--
const result = this.items[this.count]
delete this.items[this.count]
return result
}
clear() {
// 方法一
this.count = 0
this.items = {}
// 方法二
// while(!this.isEmpty()) {
// this.pop()
// }
}
toString() {
if (this.isEmpty()) return '';
let text = `${this.item[0]}`
for (let i = 1; i < this.count; i++) {
text = `${text},${this.item[i]}`
}
return text
}
}
使用
const stack = new Stack();
console.log(stack.isEmpty()); // 输出为true
stack.push(5);
stack.push(8);
console.log(stack.peek()); // 输出8
stack.push(11);
console.log(stack.isEmpty()); // 输出false
console.log(stack.size()); // 输出3
stack.push(15);
stack.pop();
stack.pop();
console.log(stack.size()); // 输出2
用栈解决问题
- 进制转换问题,十进制转n进制
function change(inputNum, type = 2) {
const digits = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
let num = inputNum
let result = ''
const stack2 = new Stack()
while(num > 0) {
stack2.push(num % type)
num = Math.floor(num / type)
}
while(!stack2.isEmpty()) {
result += digits[stack2.pop()]
}
return result
}
console.log(change(10,16))