其他没什么说的,只想说一下输出栈内元素
不要直接用stack->t或者将它赋给另一个stack,因为是指针类型。一改都改,我在这用n装下stack->t,然后进行判断,什么时候为-1就输出完成。
void print (Stack stack) {
int n = stack->t;
while (n != -1) {
printf("%d ", stack->s[n]);
n--;
}
printf("\n");
}
此处可以无需每次输入n个元素,当为字符等非整型即可终止
for (i = 0; i < n && scanf("%d", &num); i++) {
PushStack(stack, num);
}
#include<stdio.h>
#include<stdlib.h>
struct SeqStack {
int MAX;
int t;
int * s;
};
typedef struct SeqStack * Stack;
Stack CreateStack (int m) {
Stack stk = (Stack)malloc(sizeof(struct SeqStack));
int n;
if (!stk) {
printf("无内存空间\n");
return NULL;
} else {
stk->s = (int *)malloc(sizeof(int)*m);
if (stk->s) {
stk->MAX = m;
stk->t = -1;
return stk;
} else {
free(stk);
}
}
}
int IsEmpty (Stack stack) {
return (stack->t==-1)?1:0;
}
void PushStack (Stack stack, int x) {
if (stack->t >= stack->MAX-1) {
printf("上溢\n");
} else {
stack->t++;
stack->s[stack->t] = x;
}
printf("t:%d\n", stack->t);
}
void PopStack (Stack stack) {
if (stack->t == -1) {
printf("栈为空\n");
} else {
stack->t--;
printf("出栈成功\n");
}
}
int GetTopStack (Stack stack) {
if (IsEmpty(stack)) {
printf("栈为空\n");
} else {
return stack->s[stack->t];
}
}
void print (Stack stack) {
int n = stack->t;
while (n != -1) {
printf("%d ", stack->s[n]);
n--;
}
printf("\n");
}
int main(void)
{
Stack stack;
int n, num, i;
char flag;
printf("输入栈空间:");
scanf("%d", &n);
stack = CreateStack(n);
getchar();
for (i = 0; i < n && scanf("%d", &num); i++) {
PushStack(stack, num);
}
getchar();
printf("1.入栈 2.出栈\n");
printf("3.判断栈是否为空 4.输出栈元素 5.栈首元素 6.退出\n");
while (scanf("%d", &n) != EOF && n != 6) {
switch (n) {
case 1:printf("输入元素值:");scanf("%d", &n);PushStack(stack, n);break;
case 2:PopStack(stack);break;
case 3:printf("%s\n", IsEmpty(stack)==1?"空栈":"非空栈");break;
case 4:print(stack);break;
case 5:printf("栈首元素为:%d\n\n", GetTopStack(stack));break;
default:printf("请输入合法操作!\n\n"); break;
}
printf("1.入栈 2.出栈\n");
printf("3.判断栈是否为空 4.输出栈元素 5.退出\n");
}
return 0;
}