C语言单链表逆序详解:算法步骤、代码示例及优化建议
逆序单链表可以通过改变节点之间的指针方向来实现。具体步骤如下:
- 定义三个指针:prev指向当前节点的前一个节点(初始为 NULL),curr指向当前节点,next指向当前节点的下一个节点。
- 遍历单链表,循环执行以下操作: a. 将 next 指针指向 curr 节点的下一个节点。 b. 将 curr 节点的 next 指针指向 prev 节点。 c. 更新 prev 指针为 curr 节点。 d. 更新 curr 指针为 next 节点。
- 将原链表的头节点指针指向 prev 节点。
下面是一个逆序单链表的示例代码:
#include <stdio.h>
#include <stdlib.h>
// 定义单链表节点结构
struct ListNode {
int val;
struct ListNode *next;
};
// 创建单链表节点
struct ListNode* createNode(int val) {
struct ListNode* newNode = (struct ListNode*)malloc(sizeof(struct ListNode));
newNode->val = val;
newNode->next = NULL;
return newNode;
}
// 逆序单链表
struct ListNode* reverseList(struct ListNode* head) {
struct ListNode* prev = NULL;
struct ListNode* curr = head;
struct ListNode* next;
while (curr != NULL) {
next = curr->next;
curr->next = prev;
prev = curr;
curr = next;
}
return prev;
}
// 打印单链表
void printList(struct ListNode* head) {
struct ListNode* temp = head;
while (temp != NULL) {
printf("%d ", temp->val);
temp = temp->next;
}
printf("\n");
}
int main() {
// 创建一个示例单链表:1->2->3->4->5
struct ListNode* head = createNode(1);
head->next = createNode(2);
head->next->next = createNode(3);
head->next->next->next = createNode(4);
head->next->next->next->next = createNode(5);
printf("原链表:");
printList(head);
head = reverseList(head);
printf("逆序链表:");
printList(head);
return 0;
}
运行以上代码,输出结果为:
原链表:1 2 3 4 5
逆序链表:5 4 3 2 1
注意:在实际使用中,需要确保单链表的头指针指向逆序后的头节点。
优化建议:
- 可以使用迭代的方式进行单链表逆序,避免递归调用带来的栈溢出风险。
- 在实际应用中,可以考虑使用更有效率的数据结构,例如双向链表,来实现单链表的逆序操作。
原文地址: https://www.cveoy.top/t/topic/6Qu 著作权归作者所有。请勿转载和采集!