将一个字符串逆序输出。要求使用堆栈实现。c语言
时间: 2024-06-01 21:11:46 浏览: 32
#include <stdio.h>
#include <string.h>
#define MAX_SIZE 100
typedef struct {
char data[MAX_SIZE];
int top;
} Stack;
void init(Stack *s) {
s->top = -1;
}
int is_empty(Stack *s) {
return s->top == -1;
}
int is_full(Stack *s) {
return s->top == MAX_SIZE - 1;
}
void push(Stack *s, char c) {
if (is_full(s)) {
printf("Stack overflow!\n");
return;
}
s->top++;
s->data[s->top] = c;
}
char pop(Stack *s) {
if (is_empty(s)) {
printf("Stack underflow!\n");
return '\0';
}
char c = s->data[s->top];
s->top--;
return c;
}
void reverse_string(char *str) {
Stack s;
init(&s);
int len = strlen(str);
for (int i = 0; i < len; i++) {
push(&s, str[i]);
}
for (int i = 0; i < len; i++) {
str[i] = pop(&s);
}
}
int main() {
char str[MAX_SIZE];
printf("Enter a string: ");
scanf("%s", str);
reverse_string(str);
printf("Reversed string: %s\n", str);
return 0;
}
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)