《数据结构c语言版》之栈的链式存储结构(代码)

1.status.h文件

#ifndef STATUS_H
#define STATUS_H
//函数结果状态代码
#define TRUE 1
#define FALSE 0
#define OK 1
#define ERROR  0
#define INFEASIBLE -1
#define OVERFLOW -2
//Status是函数的类型,其值是函数结果状态代码
typedef int Status;
 typedef char SElemType;
typedef int ElemType;
#endif

2.ZhanLianShi.h

    #ifndef ZHANLIANSHI_H
    #define  ZHANLIANSHI_H
    #include "status.h"
    typedef struct StackNode{//这里设置链栈的结点结构
        //每个结点包含一个数据域和一个指针域
        SElemType data;
        struct StackNode *next;
    }StackNode,*pNode;//*pNode是结点的结构体指针
    
    typedef struct LinkStack{//这里设置栈顶指针
        pNode top;
        int count;
    }LinkStack;
    
    //函数声明
    void InitStack(LinkStack *ST);
    void Insert(LinkStack *ST,SElemType e);
    int Pop(LinkStack *ST,SElemType *e);
    int Print(LinkStack *ST);
    
    #endif

***3.ZhanLianShi.c***
#include "ZhanLianShi.h"
#include <stdio.h>
void InitStack(LinkStack *ST){//初始化函数
    ST->top=NULL;//top结点指向空
    ST->count=0;//置0
}

void Insert(LinkStack *ST,SElemType e){//将栈顶指针地址和将要入栈的元素传入
    pNode s=(pNode)malloc(sizeof(StackNode));//给新结点分配空间
    s->data=e;
    s->next=ST->top;
    ST->top=s;
    ST->count++;//每压入一个元素,栈的计数器加1
}

int Pop(LinkStack *ST,SElemType *e){
    pNode p;//创造一个结点p,用于存储要弹出结点的地址
    if(ST->count==0)//如果是空栈就不能弹出了
        return 0;
    p=ST->top;//存入要弹出的地址
    *e=ST->top->data;//保存要弹出的元素
    ST->top=ST->top->next;//栈顶指针向后指
    ST->count--;//计数器减1
    free(p);//释放掉弹出结点的空间
    return 1;
}

int Print(LinkStack *ST){//打印函数
    pNode H=ST->top;//定位指针
    if(H==NULL)//如果定位指针都是指向空的,说明没什么好打印的了
        return 0;
    printf("此时栈为:  ");
    printf("%d  ",H->data);
    while(H->next!=NULL){
        H=H->next;
        printf("%d  ",H->data);
    }
    printf("\n");
    return 1;
}

4ZhanLianShi_main.c

#include "ZhanLianShi.h"
#include <stdio.h>
int main(){//主函数调试
    LinkStack ST;
    int i,e;
    InitStack(&ST);
    for(i=0;i<10;i++){
        Insert(&ST,i);
    }
        Print(&ST);
    for(i=0;i<5;i++){
        Pop(&ST,&e);
        printf("弹出了一个数字%d,",e);
        Print(&ST);
        printf("\n");
    }
    Print(&ST);
}

猜你喜欢

转载自blog.csdn.net/qq_43615815/article/details/90140294