C语言 帮忙改下栈,补充完整。
发布网友
发布时间:2023-12-19 20:57
我来回答
共2个回答
热心网友
时间:2024-07-11 13:16
看看这样行不行(增加了显示栈的功能):
#include <stdio.h>
struct stack {
int arr[10];
size_t amount;
};
typedef struct stack stack_t;
int push(stack_t *stack, int s);
int pop(stack_t *stack, int *s);
void display(stack_t *stack);
int main(int argc, char *argv[]) {
stack_t stack;
int cmd, x, f;
stack.amount = 0;
while(1){
printf("\t0 pop \t1 push \t2 disp \t3 Exit\n\n");
printf("\tinput a command:");
cmd=getchar();
if(cmd=='3') break;
switch(cmd){
case '0':
f=pop(&stack, &x);
if(f)
printf("pop Error.\n");
else
printf("x=%d\n",x);
break;
case '1':
printf("x=?");
scanf("%d", &x);
f=push(&stack, x);
if(f)
printf("push Error.\n");
break;
case '2':
display(&stack);
break;
}
printf("Press any key to continue ... ");
getchar();
getchar();
}
}
int push(stack_t *stack, int s) {
if(stack->amount == 10) {
return -1;
}
stack->arr[stack->amount] = s;
stack->amount++;
return 0;
}
int pop(stack_t *stack, int *s) {
if(stack->amount == 0) {
return -1;
}
*s = stack->arr[stack->amount - 1];
stack->amount--;
return 0;
}
void display(stack_t *stack){
int i;
for(i=stack->amount-1; i>=0; i--)
printf("%d\n", stack->arr[i]);
}
热心网友
时间:2024-07-11 13:16
int main(int argc, char *argv[]) {
stack_t stack;
char s[11];
int flag, index = 0, result;
stack.amount = 0;
scanf("%s", s);
while(1){
scanf("%d", &flag);
if(flag == 1){
if(push(&stack, (int)(s[index]))){
printf("stack is full!\n");
continue;
}
index++;
printf("push %c to stack\n", s[index-1]);
}
else if(flag == 0){
if(pop(&stack, &result)){
printf("stack is empty!\n");
continue;
}
index--;
printf("pop result is %c\n", result);
}
else{
printf("invalid number!\n");
break;
}
}
return 0;
}