数据结构复习

文章提供了两个C++实现的模板类,分别用于创建自定义的栈和队列数据结构。栈和队列都包括了基本操作如push、pop以及检查是否为空或已满的方法。在主函数中,这两个数据结构被用于存储和输出数值,展示了它们的基本用法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.c++手写栈

#include <iostream>

using namespace std;
using i64 = long long;

#define fi first
#define se second
#define all(x) begin(x), end(x)
#define sz(x) (int)(x).size()
#define bug(x) cerr << x << "\n"
#define Bug(a) for (int i = 0; i < sz(a); i++) { cerr << a[i] << " "; } cerr << "\n"
typedef long double ld;
typedef pair<int, int> pii;
typedef pair<i64, i64> pll;
const int N = 1e5 + 10;
const int MOD = 998244353;
const int INF = (int) 1e9;
int dx[4] = {-1, 0, 1, 0};
int dy[4] = {0, 1, 0, -1};

template<class T>
class stack {
public:
    T stk[N];
    int top;

    stack() {
        top = 0;
    }

    bool isFull();

    bool isEmpty();

    void push(T x);

    T pop();
};

template<class T>
bool stack<T>::isFull() {
    if (top == N) {
        return 1;
    }
    return 0;
}

template<class T>
bool stack<T>::isEmpty() {
    if (top == 0) {
        return 1;
    }
    return 0;
}

template<class T>
T stack<T>::pop() {
    if (isEmpty()) {
        return -1;
    }
    return stk[--top];
}

template<class T>
void stack<T>::push(T x) {
    if (isFull()) {
        return;
    }
    stk[top++] = x;
}


int main() {

    stack<double> st;
    st.push(1.1);
    st.push(2.2);
    st.push(3.3);
    while (!st.isEmpty()) {
        cout << st.pop() << endl;
    }
    return 0;
}

2.手写队列

#include <iostream>

using namespace std;
using i64 = long long;

#define fi first
#define se second
#define all(x) begin(x), end(x)
#define sz(x) (int)(x).size()
#define bug(x) cerr << x << "\n"
#define Bug(a) for (int i = 0; i < sz(a); i++) { cerr << a[i] << " "; } cerr << "\n"
typedef long double ld;
typedef pair<int, int> pii;
typedef pair<i64, i64> pll;
const int N = 1e5 + 10;
const int MOD = 998244353;
const int INF = (int) 1e9;
int dx[4] = {-1, 0, 1, 0};
int dy[4] = {0, 1, 0, -1};

template<class T>
class queue {
public:
    T que[N];
    int head, tail;
    queue() {
        head = tail = 0;
    }
    bool isFull();
    bool isEmpty();
    void push(T x);
    T pop();
};

template<class T>
bool queue<T>::isFull() {
    if (tail == N) {
        return 1;
    }
    return 0;
}

template<class T>
bool queue<T>::isEmpty() {
    if (tail == head) {
        return 1;
    }
    return 0;
}

template<class T>
T queue<T>::pop() {
    if (isEmpty()) {
        return -1;
    }
    return que[head++];
}

template<class T>
void queue<T>::push(T x) {
    if (isFull()) {
        return;
    }
    que[tail++] = x;
}


int main() {
    queue<int> que;
    que.push(1);
    que.push(2);
    que.push(3);
    while (!que.isEmpty()) {
        cout << que.pop() << endl;
    }
    return 0;
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值