1. 程式人生 > 其它 >C語言實現線性棧

C語言實現線性棧

#include <stdio.h>
#include <stdlib.h>

#define max_size 100
typedef int SElemType;

typedef struct {
    SElemType *base;
    SElemType *top;
    int stacksize;
}SqStack;

//初始化
int InitSqStack(SqStack &S){ S.base = (SElemType *)malloc(max_size *sizeof(SqStack)); if (!S.base){ printf(
"memory error"); return 0; } S.top = S.base; S.stacksize = max_size; printf("init success \n"); return 0; }
//空棧判斷
int Empty(SqStack S){ if (S.base == S.top){ printf("empty stack\n"); return 0; } }
//求棧長
int SqStackLength(SqStack S){ printf("length is %d\n
",S.top-S.base); return 0; }
//入棧
int Push(SqStack &S, SElemType e){ if (S.top - S.base == max_size) return 0; *S.top = e; S.top ++; return 0; }
//出棧
int Pop(SqStack &S){ if (S.top == S.base) return 0; S.top--; printf("pop data is %d\n",*S.top); return 0; }
//獲取所有元素
int GetElem(SqStack S){ while(S.base!= S.top){ printf("data is %d\n",*S.base); S.base ++; } return 0; }

//清空棧
int ClearSqStack(SqStack &S){ if (S.base){ S.top = S.base; } return 0; }
//刪除棧
int DeleteSqStack(SqStack &S){ if (S.base){ free(S.base); S.base = S.top = NULL; } return 0; } int main(){ SqStack S; InitSqStack(S); for (int i=0;i<10;i++){ Push(S,i+1); } Pop(S); Pop(S); // ClearSqStack(S); DeleteSqStack(S); GetElem(S); Empty(S); SqStackLength(S); return 0; }