1.类型定义:
typedef int ElemType; typedef struct{ ElemType *elem; int top; int size; int increment; }SqStack;
调用:SqStack S;
栈窗口:
2.初始化:
//初始化顺序栈 Status InitStack_Sq(SqStack &S,int size,int inc){ S.elem=(ElemType*)malloc(size*sizeof(ElemType)); if(S.elem==NULL)return OVERFLOW; S.top=0;//置S为空栈 S.size=size; S.increment=inc; return OK; }
调用:InitStack_Sq(S,10,5);
栈窗口:
对应分配的存储空间:
3.入栈
//顺序栈元素入栈 Status Push_Sq(SqStack &S,ElemType e){ ElemType *newbase; if(S.top>=S.size){ newbase=(ElemType*)realloc(S.elem,(S.size+S.increment)*sizeof(ElemType)); if(newbase==NULL)return OVERFLOW; S.elem=newbase; S.size+=S.increment; } S.elem[S.top++]=e; return OK; }
调用:
1 int a[12]={2,3,6,9,8,7,4,0,5,1,41,45}; 2 for(int i=0;i<12;i++){ 3 Push_Sq(S,a[i]); 4 }
栈窗口:
此时i=0未把元素压入栈
当把S.size个元素压入栈后: 存储单元变化:
当压入个数大于S.size后
4.销毁:
1 //销毁顺序栈 2 Status DestroyStack_Sq(SqStack &S){ 3 free(S.elem); 4 S.elem==NULL; 5 printf("顺序栈已销毁 "); 6 }
调用:DestroyStack_Sq(S);