#include <stdio.h>#include <stdlib.h>#include <string.h>#define MAX_SIZE 100typedef struct { char data[MAX_SIZE]; int top;} Stack;void initStack(Stack *s) { s->top = -1;}void push(Stack *s, char c) { if (s->top == MAX_SIZE - 1) { printf("Stack is full!\n"); return; } s->data[++s->top] = c;}char pop(Stack *s) { if (s->top == -1) { printf("Stack is empty!\n"); return '\0'; } return s->data[s->top--];}int main() { printf("Please input a string:\n"); char str[MAX_SIZE]; fgets(str, MAX_SIZE, stdin); int len = strlen(str); Stack s; initStack(&s); for (int i = 0; i < len; i++) { switch (str[i]) { case '#': pop(&s); break; case '@': s.top = -1; break; default: push(&s, str[i]); break; } } printf("Corrected string: "); while (s.top != -1) { printf("%c", pop(&s)); } printf("\n"); return 0;}将这个代码结果改成原顺序输出怎么改
时间: 2024-01-06 21:05:06 浏览: 150
可以使用一个数组来存储字符,然后再倒序输出。修改后的代码如下:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_SIZE 100
typedef struct {
char data[MAX_SIZE];
int top;
} Stack;
void initStack(Stack *s) {
s->top = -1;
}
void push(Stack *s, char c) {
if (s->top == MAX_SIZE - 1) {
printf("Stack is full!\n");
return;
}
s->data[++s->top] = c;
}
char pop(Stack *s) {
if (s->top == -1) {
printf("Stack is empty!\n");
return '\0';
}
return s->data[s->top--];
}
int main() {
printf("Please input a string:\n");
char str[MAX_SIZE];
fgets(str, MAX_SIZE, stdin);
int len = strlen(str);
Stack s;
initStack(&s);
for (int i = 0; i < len; i++) {
switch (str[i]) {
case '#':
pop(&s);
break;
case '@':
s.top = -1;
break;
default:
push(&s, str[i]);
break;
}
}
printf("Corrected string: ");
char reverseStr[MAX_SIZE];
int index = 0;
while (s.top != -1) {
reverseStr[index++] = pop(&s);
}
for (int i = index - 1; i >= 0; i--) {
printf("%c", reverseStr[i]);
}
printf("\n");
return 0;
}
```
阅读全文