栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

线性栈 实现 C语言

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

线性栈 实现 C语言

//线性栈 

#include 
#include 
#define MAXSIZE 3
typedef int ElemType;
typedef struct {
    ElemType datas[MAXSIZE];
    int top;
} SeqStack;

// 1 栈SS的初始化操作。
void InitStack(SeqStack *S);

// 2)毁栈SS
void DestroyStack(SeqStack *S);

// 3)清空栈
void ClearStack(SeqStack *S);

// 4)元素入栈,若栈存在,插入数据e为栈顶元素,返回0操作失败,1操作成功
int Push(SeqStack *S, ElemType e);

// 5)元素出栈,若栈存在,删除栈顶数据,返回值到e,返回0操作失败,1操作成功
int Pop(SeqStack *S, ElemType *e);

// 6)判断栈是否为空,返回值:1-空,0-非空或失败。
int IsEmpty(SeqStack S);

// 7)判断栈是已满,1 - 已满 0- 未满或失败。
int IsFull(SeqStack S);

// 8)求栈的长度,返回栈S元素的个数。返回值为长度
int Length(SeqStack S);

// 9)取栈顶元素返用e返回其值,返回0操作失败,1操作成功
void GetTop(SeqStack S, ElemType *e);

// 10)打印顺序栈中的全部元素
void PrintStack(SeqStack S);


int main() {
    SeqStack S;
    ClearStack(&S);
    while (1) {
        int q = 0;
        printf("是否入栈? 1/0 :");
        scanf("%d", &q);
        if (q == 1) {
            int e;
            printf("输入入栈数据: b");
            scanf("%d", &e);
            Push(&S, e);
            q = 0;
        }
        printf("是否出栈? 1/0 :");
        scanf("%d", &q);
        if (q == 1) {
            int e;
            Pop(&S, &e);
            printf("出栈数据:%dn",e);
            q = 0;
        }
        printf("栈中元素个数为:%dn",Length(S));
        PrintStack(S);
    }

    return 0;
}

// 1 栈SS的初始化操作。
void InitStack(SeqStack *S);

// 2)毁栈SS
void DestroyStack(SeqStack *S);

// 3)清空栈
void ClearStack(SeqStack *S) {
    S->top = -1;
}

// 4)元素入栈,若栈存在,插入数据e为栈顶元素
int Push(SeqStack *S, ElemType e) {
    if (S->top == MAXSIZE - 1) {
        printf("栈已满,无法入栈.n");
        return 0;
    }
    S->datas[++S->top] = e; //赋值且栈顶加一
    return 1;
}


// 5)元素出栈,若栈存在,删除栈顶数据,返回值到e
int Pop(SeqStack *S, ElemType *e) {
    if (S->top == -1) {
        printf("栈为空,无法出栈.n");
        return 0;
    }
    *e = S->datas[S->top--];
    return 1;
}

// 6)判断栈是否为空,值:1-空,0-非空或失败。
int IsEmpty(SeqStack S) {
    if (S.top == -1) {
        return 1;
    }
    return 0;
}

// 7)判断栈是已满,1 - 已满 0- 未满或失败。
int IsFull(SeqStack S) {
    if (S.top == MAXSIZE - 1) {
        return 1;
    }
    return 0;
}

// 8)求栈的长度,返回栈S元素的个数。
int Length(SeqStack S){
    return S.top+1;
}

// 9)取栈顶元素返用e返回其值
void GetTop(SeqStack S, ElemType *e) {
    if (S.top == -1) {
        printf("栈为空,无法取栈顶元素.n");
    }
    *e = S.datas[S.top];
}

// 10)打印顺序栈中的全部元素
void PrintStack(SeqStack S) {
    printf("栈中数据为:"); 
    for (int i = 0; i <= S.top; i++) {
        printf("%d ", S.datas[i]);
    }
    printf("n");
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/779947.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号