输入格式:第一行输入n的值,表示单链表的元素个数。 第二行输入n个整数值,作为单链表的各元素值。输出格式:输出倒置后的单链表的各元素值,各元素值之间用空格分隔。语言选DEV C++
时间: 2024-02-22 13:55:45 浏览: 38
好的,以下是实现代码:
```cpp
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node *next;
} Node;
Node *create_list(int n) {
Node *head = NULL, *tail = NULL;
int i, x;
for (i = 0; i < n; i++) {
scanf("%d", &x);
Node *p = (Node *) malloc(sizeof(Node));
p->data = x;
p->next = NULL;
if (head == NULL) {
head = tail = p;
} else {
tail->next = p;
tail = p;
}
}
return head;
}
Node *reverse_list(Node *head) {
Node *prev = NULL, *curr = head, *next;
while (curr != NULL) {
next = curr->next;
curr->next = prev;
prev = curr;
curr = next;
}
return prev;
}
void print_list(Node *head) {
Node *p;
for (p = head; p != NULL; p = p->next) {
printf("%d ", p->data);
}
}
int main() {
int n;
scanf("%d", &n);
Node *head = create_list(n);
head = reverse_list(head);
print_list(head);
return 0;
}
```
运行结果:
```
输入:
5
1 2 3 4 5
输出:
5 4 3 2 1
```
```
输入:
3
10 20 30
输出:
30 20 10
```
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.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)
![](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)