复制代码
#include <iostream>
#include <string.h>
using namespace std;
typedef int SElemType;
typedef struct StackNode {
    SElemType data;
    struct StackNode* next;
}StackNode,*LinkStack;
//初始化链栈
void InitStack(LinkStack &S) {
    S = NULL;
}
//入栈
bool EnterStack(LinkStack &S,int e) {
    StackNode* p = new StackNode;
    if (!p)return false;
    p->data = e;
    p->next = S;
    S = p;
    return true;
}
//出栈
bool PopStack(LinkStack& S, int &e) {
    if (!S)return false;
    e = S->data;
    StackNode* q = S;
    S = S->next;
    delete q;
    return true;
}
//取栈顶的元素
int GetTop(LinkStack& S) {
    if (S) {
        return S->data;
    }
    else {
        return -1;
    }
}
//打印输出栈元素
void PrintStack(LinkStack& S) {
    LinkStack i = S;
    cout << "链栈的元素为:";
    while (i!=NULL) {
        cout <<  i->data <<" ";
        i = i->next;
    }
    cout << endl;
}
int main(void) {
    LinkStack S;
    int count = 0;//入栈元素个数
    int count1 = 0;//出栈元素个数
    int e = 0;
    //初始化
    InitStack(S);
    //入栈
    cout << "请输入入栈元素个数:";
    cin >> count;
    while (count > 0) {
        cout << "请输入要入栈的元素:";
        cin >> e;
        if (EnterStack(S, e)) {
            cout << "元素 " << e << " 入栈成功!" << endl;
            //取栈顶元素
            cout << "此时的栈顶元素为:" << GetTop(S) << endl;
        }
        else {
            cout << "元素 " << e << " 入栈失败!" << endl;
        }
        count--;
    }
    //出栈
    cout << "请输入要出栈的元素个数:";
    cin >> count1;
    while (count1>0) {
        if (PopStack(S, e)) {
            cout << "元素 " << e << " 出栈成功!" << endl;
            count1--;
        }
        else {
            cout << "元素 " << e << " 出栈失败!" << endl;
        }
    }
    //打印输出剩余的栈元素
    PrintStack(S);
    system("pause");
    return 0;
}
复制代码

posted on   wshidaboss  阅读(45)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
< 2025年3月 >
23 24 25 26 27 28 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 1 2 3 4 5

点击右上角即可分享
微信分享提示