栈:栈是一种特殊的线性表。其特殊性在于限定插入和删除数据元素的操作只能在线性表的一端进行。
/** ** 2017.11.3 ** Ahthor:799 ** 栈的顺序实现 ** ***/ #include <bits/stdc++.h> using namespace std; #define STACK_INIT_SIZE 100 /// 存储空间初始分配 #define STACK_INCREMENT 10 /// 存储空间分配增量 #define ElemType int #define Status int #define OK 1 #define ERROR -1 #define OVERFLOW -2 typedef struct { ElemType *base; ElemType *top; int stacksize; } SqStack; Status InitStack (SqStack &S) { S.base = (ElemType * )malloc(STACK_INIT_SIZE * sizeof(ElemType)); if (!S.base) exit(OVERFLOW); S.top = S.base; S.stacksize = STACK_INIT_SIZE; return OK; } Status DestroyStack(SqStack &S) { for (ElemType *index = S.base; index != S.top; index ++) { free(index); } free(&S); return OK; } Status ClearStack(SqStack &S) { for (ElemType *index = S.base+1; index != S.top; index ++) { free(index); } S.top = S.base; return OK; } Status IsEmptyStack(SqStack &S) { if (S.base == S.top) return true; else return false; } Status LengthStack(SqStack &S) { return S.top - S.base; } ElemType GetTop(SqStack &S) { if (S.top == S.base) return ERROR; ElemType e = *(S.top - 1); return e; } Status Push(SqStack &S,ElemType &e) { if (S.top - S.base >= S.stacksize) { S.base = (ElemType *) realloc (S.base,(S.stacksize + STACK_INCREMENT) * sizeof(ElemType)); if (!S.base)exit(OVERFLOW); S.top = S.base + S.stacksize; S.stacksize += STACK_INCREMENT; } *S.top = e; S.top ++; return OK; } Status Pop(SqStack &S, ElemType &e) { if (S.top == S.base) return ERROR; e = * --S.top; return OK; } Status TrverseStack(SqStack &S) { for (ElemType *index = S.base; index != S.top; index ++) { cout<<*index<<" "; } cout<<endl; return OK; } int main() { SqStack * St = (SqStack *) malloc(sizeof(SqStack)); InitStack (*St); int n; cin>>n; while (n--) { int tmp; cin>>tmp; Push(*St,tmp); } int num; Pop(*St,num); cout<<" num "<<num<<endl; TrverseStack(*St); cout<<" top "<<GetTop(*St)<<endl; cout<<" len : "<<LengthStack(*St)<<endl; ClearStack(*St); if (IsEmptyStack(*St)) cout<<" kong "<<endl; else cout<<" no "<<endl; return 0; }