从键盘读入一个字符串,把它存入一个链表(每个结点存储1个字符),并按相反的次序将字符串输出到显示屏。
时间: 2024-04-29 22:26:21 浏览: 18
好的,我可以帮你解决这个问题。可以使用C语言的链表来存储字符串中的每个字符,然后将链表中的字符按照相反的顺序输出到屏幕上。以下是一个示例代码:
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct Node {
char data;
struct Node* next;
} Node;
void push(Node** head, char data) {
Node* new_node = (Node*) malloc(sizeof(Node));
if (new_node == NULL) {
printf("Error: Memory allocation failed.\n");
exit(1);
}
new_node->data = data;
new_node->next = *head;
*head = new_node;
}
void print_reverse(Node* head) {
if (head == NULL) {
return;
}
print_reverse(head->next);
printf("%c", head->data);
}
int main() {
char str[100];
printf("Please enter a string: ");
fgets(str, 100, stdin);
int len = strlen(str);
if (str[len - 1] == '\n') {
str[len - 1] = '\0';
}
Node* head = NULL;
for (int i = 0; i < len; i++) {
push(&head, str[i]);
}
printf("Reversed string: ");
print_reverse(head);
printf("\n");
return 0;
}
```
这个程序通过调用 `fgets` 函数从键盘读入一个字符串(最多100个字符),并使用 `push` 函数将字符串中的每个字符存储到链表中。然后使用 `print_reverse` 函数将链表中的字符按反向顺序输出到屏幕上。注意,在输入字符串后,需要用 `strlen` 函数获取字符串的长度,并且在字符串的末尾添加一个 null 字符,以确保字符串以正确的方式被处理。