#include
#include
// 定義棧結(jié)構(gòu)體
typedef struct {
??int *data; // 棧中數(shù)據(jù)的指針
??int top; // 棧頂指針
??int size; // 棧的大小
} SeqStack;
// a. 對棧動(dòng)態(tài)分配內(nèi)存
void initStack(SeqStack *S, int size) {
??S->data = (int *)malloc(sizeof(int) * size);
??S->top = -1;
??S->size = size;
}
// b. 初始化棧
void createStack(SeqStack *S) {
??int data;
??printf("請輸入棧的元素?cái)?shù)量:");
??int n;
??scanf("%d", &n);
??printf("請依次輸入棧的元素:\n");
??for (int i = 0; i < n; i++) {
????scanf("%d", &data);
????S->data[++S->top] = data;
??}
}
// c. 取棧頂元素的值
int top(SeqStack *S) {
??if (S->top == -1) {
????printf("棧為空,無法取棧頂元素。\n");
????return -1;
??}
??return S->data[S->top];
}
// d. 在棧頂插入元素
void push(SeqStack *S, int data) {
??if (S->top == S->size - 1) {
????printf("棧已滿,無法插入元素。\n");
????return;
??}
??S->data[++S->top] = data;
}
// e. 出棧操作
int pop(SeqStack *S) {
??if (S->top == -1) {
????printf("棧為空,無法出棧。\n");
????return -1;
??}
??int data = S->data[S->top--];
??return data;
}
// f. 遍歷棧中元素
void traverse(SeqStack *S) {
??if (S->top == -1) {
????printf("棧為空。\n");
????return;
??}
??printf("棧中元素為:\n");
??for (int i = S->top; i >= 0; i--) {
????printf("%d ", S->data[i]);
??}
??printf("\n");
}
int main() {
??SeqStack S;
??initStack(&S, 10);
??createStack(&S);
??printf("棧頂元素為:%d\n", top(&S));
??push(&S, 10);
??printf("插入后棧頂元素為:%d\n", top(&S));
??printf("出棧的元素為:%d\n", pop(&S));
??traverse(&S);
??return 0;
}
標(biāo)簽: