栈结构

8/18/2022 数据结构

# 一个先进后出的数据结构

javascript中没有栈,但可以用array实现栈道所有

   <script>
        // 封装栈类
        function Stack() {
            // 栈道属性
            this.items = []

            // 栈的操作
            // 1. 将元素压入到栈
            Stack.prototype.push = function (element) {
                return this.items.push(element)
            }
            // 2. 从栈中js取出元素
            Stack.prototype.pop = function (element) {
                return this.items.pop()
            }
            // 3. 查看一下栈顶元素
            Stack.prototype.peek = function (element) {
                return this.items[this.items.length - 1]
            }
            // 4. 判断栈是否为空
            Stack.prototype.isEmpty = function (element) {
                return this.items.length == 0
            }
            // 5. 获取栈中元素的个数
            Stack.prototype.size = function (element) {
                return this.items.length
            }
            // 6. tostring方法
            Stack.prototype.toString = function (element) {
                return this.items.join(' ')
            }
        }

        let s = new Stack()
        s.push(10)
        s.push(20)
        s.push(30)

        console.log(s)
        console.log(s.isEmpty())


        // 将十进制转二进制
        function dec2bin(decNumber) {
            let stack = new Stack()

            while (decNumber > 0) {
                // 1. 获取余数,压入栈中
                stack.push(decNumber % 2)

                // 2. 获取整除的结果
                decNumber = Math.floor(decNumber / 2)
            }
            let binaryString = ''
            while (!stack.isEmpty()) {
                binaryString += stack.pop()
            }

            return binaryString
        }

        console.log(dec2bin(100))


    </script>
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
57
58
59
60
61
62
63
64
65