Skip to content

Commit 0bc0cc2

Browse files
committed
add stack
1 parent 982fcbb commit 0bc0cc2

2 files changed

Lines changed: 35 additions & 3 deletions

File tree

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,17 @@
11
/*
22
* 栈的实现
33
*/
4-
function Stack() {
4+
module.exports = function Stack() {
5+
// 栈中的属性、方法
56
this.dataStore = [];
7+
// 栈顶计数
68
this.top = 0;
79
this.push = push;
810
this.pop = pop;
911
this.peek = peek;
1012
this.clear = clear;
11-
this.length = length;
13+
this.size = size;
14+
this.isEmpty = isEmpty;
1215
}
1316

1417
// 往栈中推入数据
@@ -32,7 +35,12 @@ function clear() {
3235
}
3336

3437
// 返回栈的长度
35-
function length() {
38+
function size() {
3639
return this.top;
3740
}
3841

42+
// 判断是否为空
43+
function isEmpty() {
44+
return this.top === 0;
45+
}
46+

‎JavaScript/Stack/Test.js‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
const Stack = require('./Stack');
2+
3+
// 定义将10进制的数转换为2进制
4+
function dec2bin(decNumber) {
5+
var stack = new Stack();
6+
var remainder;
7+
8+
// 循环除法
9+
while(decNumber > 0) {
10+
remainder = decNumber % 2;
11+
decNumber = Math.floor(decNumber / 2);
12+
stack.push(remainder);
13+
}
14+
// 取出数据
15+
var binStr = "";
16+
while(!stack.isEmpty()) {
17+
binStr += stack.pop();
18+
}
19+
console.log(binStr);
20+
return binStr;
21+
}
22+
23+
// 测试函数
24+
console.log(dec2bin(10));

0 commit comments

Comments
 (0)