概念

队列是一种线性存储的数据结构

原则:

  • 后进先出 - **LIFO **( last in first out)
  • 先进后出

规则:

  • 栈顶 - 插入、删除
  • 栈底
  • 空栈

es5 实现栈:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
function Stack() {
this.temp = [];
}

Stack.prototype.push = function (element) {
this.temp.push(element);
};
// 移除栈顶的元素, 同时返回被移除的元素
Stack.prototype.pop = function () {
return this.temp.pop(this.temp.length - 1);
};
// 返回栈顶元素,不对栈元素做任何修改
Stack.prototype.peek = function () {
return this.temp[this.temp.length - 1];
};
// 判断栈是否为空, 为空返回true, 否则返回false
Stack.prototype.isEmpty = function () {
return this.temp.length == 0;
};
// 移除栈里的所有元素
Stack.prototype.clear = function () {
this.temp.length = 0;
};
// 返回栈中的元素个数
Stack.prototype.size = function () {
return this.temp.length;
};
Stack.prototype.print = function () {
return this.temp.toString();

es6 实现栈:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
class Stack {
temp = [];
// 没有继承父类(基类)可以省略constructor
// constructor() {
// this.temp = [];
// }

push(element) {
this.temp.push(element);
}
// 移除栈顶的元素, 同时返回被移除的元素
pop() {
return this.temp.pop(this.temp.length - 1);
}
// 返回栈顶元素,不对栈元素做任何修改
peek() {
return this.temp[this.temp.length - 1];
}
// 判断栈是否为空, 为空返回true, 否则返回false
isEmpty() {
return this.temp.length == 0;
}
// 移除栈里的所有元素
clear() {
this.temp.length = 0;
}
// 返回栈中的元素个数
size() {
return this.temp.length;
}
print() {
return this.temp.toString();
}
}

// number 10进制
// base 转为多少进制的数
function baseConverter(number, base) {
let rem;
let baseString = "";
let digist = "0123456789ABCDEF";
let stack = new Stack();

while (number > 0) {
rem = Math.floor(number % base);
stack.push(rem);
number = Math.floor(number / base);
}
while (!stack.isEmpty()) {
console.log(stack.pop());
baseString += digist[stack.pop()];
}
return baseString;
}

console.log(baseConverter(100345, 32));
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
class Stack {
constructor() {
this.stackList = [];
}
// 入栈
push(arg) {
this.stackList.unshift(arg);
}
// 出栈
pop() {
return this.stackList.shift();
}
// 栈顶元素
top() {
return this.stackList[0];
}
print() {
console.log(this.stackList.toString());
}
isEmpty() {
return this.stackList.length > 1 ? false : true;
}
size() {
return this.stack.length;
}
clear() {
this.stackList = [];
}
}

const stack = new Stack();

const array = [1, 2, 3, 4, 5];
array.forEach((arr) => {
stack.push(arr);
});

console.log(stack.print());
console.log(stack.pop());
console.log(stack.print());