LongDz 的数字文墨提案

📄 data_struct/共享栈.cpp
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
#include <iostream>
using namespace std;

template <class T, int N = 1024>
class TwoStack
{
public:
    TwoStack() : top1(-1), top2(N) {}

    // 第一个栈(左侧)
    void Push1(const T &x)
    {
        if (top1 + 1 == top2)
            throw "栈满";
        data[++top1] = x;
    }
    T Pop1()
    {
        if (Empty1())
            throw "栈1为空";
        return data[top1--];
    }
    T Top1() const
    {
        if (Empty1())
            throw "栈1为空";
        return data[top1];
    }
    bool Empty1() const { return top1 == -1; }
    int Size1() const { return top1 + 1; }

    // 第二个栈(右侧)
    void Push2(const T &x)
    {
        if (top1 + 1 == top2)
            throw "栈满";
        data[--top2] = x;
    }
    T Pop2()
    {
        if (Empty2())
            throw "栈2为空";
        return data[top2++];
    }
    T Top2() const
    {
        if (Empty2())
            throw "栈2为空";
        return data[top2];
    }
    bool Empty2() const { return top2 == N; }
    int Size2() const { return N - top2; }

    // 剩余可用空间
    int FreeSpace() const { return top2 - top1 - 1; }

private:
    T data[N];
    int top1; // 初始 -1,向右增长
    int top2; // 初始 N,向左增长