栈的链式存储

2020/12/27

# Heading

# 定义

采用链式存储的栈称为链栈,链栈的优点是便于多个栈共享存储空间提高其效率,且不存在栈满上溢的情况。通常采用单链表实现,并规定所有操作都是在单链表的表头进行的。

# 链栈的实现

实现带头结点的链栈如下:

/**
 * 链式栈
 */

import { ListNode } from './Node'
class LinkStack {
    constructor() {
        this.top = new ListNode();
    }

    InitStack(...args) {
        this.top = new ListNode();
        args.forEach(item => this.Push(item))
    }
    StackEmpty() {
        return this.top.next === null
    }
    Push(value) {
        const p = new ListNode(value, this.top.next);
        this.top.next = p;
    }
    Pop() {
        let ret

        if (!this.StackEmpty()) {
            ret = this.top.next.value
            this.top.next = this.top.next.next
        }
        return ret
    }
    GetTop() {
        return this.StackEmpty() ? undefined : this.top.next.value
    }
}

export {
    LinkStack
}
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