結構定義
#define MAXSIZE 1000
typedef int ElemType;
typedef struct {
ElemType data[MAXSIZE];
int top; // -1 為空
} SqStack;
核心操作
void InitStack(SqStack *&s) { s = (SqStack*)malloc(sizeof(SqStack)); s->top = -1; }
void DestroyStack(SqStack *&s) { free(s); s = NULL; }
int StackEmpty(SqStack *s) { return s->top == -1; }
int StackLength(SqStack *s) { return s->top + 1; }
int Push(SqStack *&s, ElemType e) {
if (s->top + 1 == MAXSIZE) return 0;
s->data[++s->top] = e; return 1;
}
int Pop(SqStack *&s, ElemType &e) {
if (s->top == -1) return 0;
e = s->data[s->top--]; return 1;
}
int GetTop(SqStack *s, ElemType &e) {
if (s->top == -1) return 0;
e = s->data[s->top]; return 1;
}
void DispStack(SqStack *s) {
for (int i=s->top; i>=0; --i) printf("%d ", s->data[i]);
puts("");
}
測試主函數
int main() {
SqStack *s = NULL; InitStack(s);
int a[] = {3,76,4,25,7,8,2,43,212};
for (int x : a) { Push(s,x); DispStack(s); }
ElemType e; GetTop(s,e); printf("Top=%d Len=%d\n", e, StackLength(s));
while (!StackEmpty(s)) { Pop(s,e); DispStack(s); }
DestroyStack(s);
return 0;
}
要點
top 初始 -1,指向棧頂元素。
- 指針傳引用
SqStack *&s 以便修改指針本身(如初始化、銷毀)。
- 返回
int 表示成功/失敗,避免異常。