单链表逆置(就地逆序) C语言实现

这篇博客介绍了如何使用C语言实现单链表的逆置操作。通过定义链表结构体,初始化链表,插入元素,计算链表长度以及实现逆置函数,实现了链表的就地逆序。主要涉及的函数包括`initList`用于创建链表,`insertList`用于插入元素,`length`计算链表长度,以及`reverse`进行链表逆置。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

LinkList.h

 

 

LinkList.c

单链表就地是指不引入新的节点,只调整原有节点的指针,将单链表逆序排列。 实现单链表就地可以使用三个指针:prev、curr和next。开始时,将prev指向NULL,curr指向链表的首节点,next指向curr的下一个节点。 接下来,通过循环遍历单链表,每次将curr的指针指向prev,然后将prev、curr和next指针都向后移动一个节点。直到curr指向NULL,表示已经遍历到链表的末尾。 最后,将链表的头节点指向prev,完成就地。 以下是C语言实现的代码示例: #include <stdio.h> struct Node { int data; struct Node* next; }; // 单链表就地函数 void reverseList(struct Node** head){ struct Node* prev = NULL; struct Node* curr = *head; struct Node* next = NULL; while(curr != NULL){ next = curr->next; curr->next = prev; prev = curr; curr = next; } *head = prev; } // 打印单链表函数 void printList(struct Node* head){ struct Node* temp = head; while(temp != NULL){ printf("%d ", temp->data); temp = temp->next; } printf("\n"); } int main(){ // 创建一个示例单链表: 1 -> 2 -> 3 -> 4 -> 5 struct Node* head = NULL; struct Node* second = NULL; struct Node* third = NULL; struct Node* fourth = NULL; struct Node* fifth = NULL; head = (struct Node*)malloc(sizeof(struct Node)); second = (struct Node*)malloc(sizeof(struct Node)); third = (struct Node*)malloc(sizeof(struct Node)); fourth = (struct Node*)malloc(sizeof(struct Node)); fifth = (struct Node*)malloc(sizeof(struct Node)); head->data = 1; head->next = second; second->data = 2; second->next = third; third->data = 3; third->next = fourth; fourth->data = 4; fourth->next = fifth; fifth->data = 5; fifth->next = NULL; printf("原始链表: "); printList(head); reverseList(&head); printf("就地后的链表: "); printList(head); return 0; } 运行此程序,输出结果为: 原始链表: 1 2 3 4 5 就地后的链表: 5 4 3 2 1
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值