c语言:输入10个数字,并根据这些数字构造单向链表,之后,再反转链表并打印输出,即A={a1,a2,…,a_n}反转成A={a_n,…,a2,a1} 输入提示: "Please input %d numbers:\n" 输入格式: "%d" 输出格式: "%5d" 程序运行结果实例1: Please input 10 numbers: ↙ 1 2 3 4 5 6 7 8 9 10 10 9 8 7 6 5 4 3 2 1
时间: 2024-01-02 10:05:26 浏览: 63
以下是实现该功能的C语言代码:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义链表节点结构体
struct Node {
int data;
struct Node* next;
};
// 反转链表
struct Node* reverseList(struct Node* head) {
struct Node* prev = NULL;
struct Node* curr = head;
while (curr != NULL) {
struct Node* next = curr->next;
curr->next = prev;
prev = curr;
curr = next;
}
return prev;
}
int main() {
int n = 10;
printf("Please input %d numbers:\n", n);
// 构造链表
struct Node* head = NULL;
struct Node* tail = NULL;
for (int i = 0; i < n; i++) {
int num;
scanf("%d", &num);
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = num;
newNode->next = NULL;
if (head == NULL) {
head = newNode;
tail = newNode;
} else {
tail->next = newNode;
tail = newNode;
}
}
// 反转链表
head = reverseList(head);
// 打印链表
printf("Output:\n");
struct Node* curr = head;
while (curr != NULL) {
printf("%5d", curr->data);
curr = curr->next;
}
return 0;
}
```
输入示例:
```
Please input 10 numbers:
1 2 3 4 5 6 7 8 9 10
```
输出示例:
```
Output:
10 9 8 7 6 5 4 3 2 1
```
阅读全文