標籤:
#include <stdio.h>
#include <stdlib.h>
#define STACK_INIT_SIZE 100
#define STACKINCREMENT 10
#define OVERFLOW -2
#define OK 1
#define ERROR 0
typedef int SElemType;
//棧結構體
typedef struct {
SElemType *base;
SElemType *top;
int stacksize;
}SqStack;
//函數定義
int InitStack(SqStack *S);
int GetTop(SqStack *S,SElemType *e);
int Push(SqStack *S,SElemType e);
int DestoryStack(SqStack *S);
int StackEmpty(SqStack *S);
int StackLength(SqStack *S);
int Pop(SqStack *S,SElemType *e);
int StackTraverse(SqStack *S);
int main()
{
SqStack *sq;
int f1,f2,e,f3,i,n,a,f4,f5,len,f6,f7;
//初始化棧
f1 = InitStack(sq);
if(f1) printf("初始化棧成功!\n");
else printf("初始化棧失敗!\n");
//入棧
printf("請輸入棧中元素的個數:");
scanf("%d",&n);
printf("請輸入棧中元素:");
for(i=0; i<n; i++) {
scanf("%d",&a);
Push(sq,a);
}
//取得棧頂元素
f2 = GetTop(sq,&e);
if(f2) printf("棧頂元素為:%d\n",e);
else printf("棧為空白!無棧頂元素!\n");
//判斷棧是否為空白
f5 = StackEmpty(sq);
if(f5) printf("棧為空白!\n");
else printf("棧不為空白!\n");
//刪除棧中的元素
f6 = Pop(sq,&e);
if(f6) {
printf("刪除的元素為:%d\n",e);
}
//取得棧的長度
len = StackLength(sq);
printf("棧的長度為:%d\n",len);
//自頂向下遍曆棧
StackTraverse(sq);
//銷毀棧
f4 = DestoryStack(sq);
if(f4) printf("銷毀棧成功!\n");
else printf("銷毀棧失敗!\n");
return 0;
}
//初始化棧
int InitStack(SqStack *S) {
S->base = (SElemType *)malloc(STACK_INIT_SIZE*sizeof(SElemType));
if(!S->base) {
exit(OVERFLOW);
}
S->top = S->base;
S->stacksize = STACK_INIT_SIZE;
return OK;
}
//取得棧頂元素
int GetTop(SqStack *S,SElemType *e) {
if(S->top == S->base) {
return ERROR;
}
*e = *(S->top-1);
return OK;
}
//入棧
int Push(SqStack *S,SElemType 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++ = e;
return OK;
}
//刪除棧中的元素
int Pop(SqStack *S,SElemType *e) {
if(S->top == S->base) return ERROR;
*e = *--S->top;
return OK;
}
//銷毀棧
int DestoryStack(SqStack *S) {
S->top = S->base;
free(S->base);
S->top = NULL;
S->base = NULL;
return OK;
}
//判斷棧是否為空白
int StackEmpty(SqStack *S) {
if(S->top == S->base) {
return OK;
}
return ERROR;
}
//取得棧的長度
int StackLength(SqStack *S) {
return S->top-S->base;
/*int i=0;
if(!StackEmpty(S)) {
while(S->top!=S->base) {
i++;
S->top--;
}
}
return i;*/
}
//自頂向下遍曆棧
int StackTraverse(SqStack *S) {
SElemType *p;
if(S->base!=S->top) {
printf("棧中自頂向下的元素為:");
p = S->top;
while(p!=S->base) {
p--;
printf("%d ",*p);
}
} else {
printf("棧為空白!\n");
return ERROR;
}
printf("\n");
return OK;
}
資料結構-棧有關操作演算法