链表倒置,编写c程序
时间: 2024-05-26 17:07:39 浏览: 9
链表倒置指的是将链表中所有节点的顺序颠倒,变成原来的逆序。这可以通过遍历链表并调整节点之间的指针关系来实现。
下面是一个简单的C程序,实现链表倒置:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义链表节点
struct node {
int data;
struct node* next;
};
// 创建新的链表节点
struct node* create_node(int data) {
struct node* new_node = (struct node*)malloc(sizeof(struct node));
new_node->data = data;
new_node->next = NULL;
return new_node;
}
// 将链表倒置
struct node* reverse_list(struct node* head) {
struct node *prev = NULL, *curr = head, *next = NULL;
while (curr != NULL) {
next = curr->next; // 先保存下一个节点
curr->next = prev; // 当前节点的下一个指向前一个节点
prev = curr; // 更新前一个节点
curr = next; // 更新当前节点
}
return prev; // 返回新的头节点
}
// 打印链表
void print_list(struct node* head) {
while (head != NULL) {
printf("%d ", head->data);
head = head->next;
}
printf("\n");
}
int main() {
// 创建链表
struct node* head = create_node(1);
head->next = create_node(2);
head->next->next = create_node(3);
head->next->next->next = create_node(4);
printf("原链表: ");
print_list(head);
// 倒置链表
struct node* new_head = reverse_list(head);
printf("倒置后的链表: ");
print_list(new_head);
return 0;
}
```
相关推荐
![](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)