顺序栈,即栈的顺序存储结构,是利用一组连续的地址单元依次存放自栈底到栈顶的数据元素。同时为栈结构设置栈底指针base与栈顶指针top。若base=NULL,则表明栈结构不存在。top指针初值指向栈底,top=base可用作栈为空的标记。新插入元素后栈顶指针top的值加1,删除元素时减1。即非空栈的栈顶指针top始终在栈顶元素的下一个位置上。
//------------------------栈的顺序实现----------------------// #include <stdio.h> #include <stdlib.h> #define STACK_INIT_SIZE 8 #define STACKINCREMENT 5 #define Status int #define OK 1 #define ERROR 0 #define OVERFLOW -2 typedef struct SElemType { int data; }SElemType; //构造结点 typedef struct { SElemType *base; SElemType *top;//非空栈的栈顶指针始终在栈顶元素的下一位置 int stacksize; }SqStack; // 构造栈 Status IsEmpty(SqStack S) { if(S.top == S.base) return OK; return ERROR; } Status InitStack(SqStack *S) { //构造一个空栈 S->base=(SElemType *)malloc( STACK_INIT_SIZE *sizeof( SElemType)); S->top=S->base; S->stacksize=STACK_INIT_SIZE; return OK; } Status GetTop(SqStack S, SElemType *e) { if( S.top == S.base) return ERROR; e->data=(S.top-1)->data; return OK; } Status Push(SqStack *S, SElemType e) { //插入的e为新的栈顶元素 if(S->top -S->base >= S->stacksize) { S->base=(SElemType *)realloc(S->base, (S->stacksize + STACKINCREMENT) * sizeof( SElemType)); if( !S->base) exit(OVERFLOW); S->top = S->base + S->stacksize; S->stacksize += STACKINCREMENT; } S->top->data=e.data; S->top++; return OK; } Status Pop(SqStack *S, SElemType *e) { //若栈不为空则返回栈顶元素,并返回OK,否则返回ERROR if( S->top == S->base) return ERROR; *e=*--S->top; return OK; } void Print(SqStack S) { while( S.top != S.base) { printf("%d ",(S.top-1)->data); S.top--; } printf("\n"); } int main(void) { SqStack S; SElemType e; int i; InitStack(&S); if( IsEmpty(S)) printf("the stack has nothing installled.。pplese enter:\n"); for(i=0; i<S.stacksize; i++) { scanf("%d", &e.data); Push(&S, e); } GetTop(S, &e); printf("top=%d\n", e.data); Print(S); Pop(&S, &e); printf("after pop %d,members in stack are:\n",e.data); Print(S); return 0; }
运行结果:
原文地址:http://blog.csdn.net/codebat/article/details/40296281