设计算法实现将单链表中数据逆置后输出。用C语言代码
时间: 2024-04-29 15:27:14 浏览: 273
如下所示:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义单链表节点结构体
struct node {
int data;
struct node *next;
};
// 定义单链表逆置函数
struct node* reverse(struct node *head) {
struct node *prev = NULL;
struct node *curr = head;
struct node *next;
while (curr != NULL) {
next = curr->next;
curr->next = prev;
prev = curr;
curr = next;
}
return prev;
}
// 定义单链表输出函数
void print_list(struct node *head) {
struct node *p = head;
while (p != NULL) {
printf("%d ", p->data);
p = p->next;
}
printf("\n");
}
int main() {
// 定义单链表 head 节点并初始化
struct node *head = (struct node*)malloc(sizeof(struct node));
head->data = 1;
// 定义单链表节点 a, b, c 并初始化
struct node *a = (struct node*)malloc(sizeof(struct node));
a->data = 2;
struct node *b = (struct node*)malloc(sizeof(struct node));
b->data = 3;
struct node *c = (struct node*)malloc(sizeof(struct node));
c->data = 4;
// 手动建立单链表
head->next = a;
a->next = b;
b->next = c;
c->next = NULL;
printf("反转前:\n");
print_list(head);
// 调用单链表反转函数
head = reverse(head);
printf("反转后:\n");
print_list(head);
return 0;
}
```
输出:
```
反转前:
1 2 3 4
反转后:
4 3 2 1
```
阅读全文