要实现单链表的反转,可以按照以下步骤进行:
下面是使用C语言实现单链表反转的代码示例:
#include <stdio.h>
#include <stdlib.h>
// 定义链表节点结构体
typedef struct Node {
int data;
struct Node* next;
} Node;
// 定义链表反转函数
void reverseList(Node** head) {
Node* current = *head;
Node* prev = NULL;
Node* next = NULL;
while (current != NULL) {
next = current->next;
current->next = prev;
prev = current;
current = next;
}
*head = prev;
}
// 定义链表打印函数
void printList(Node* head) {
Node* current = head;
while (current != NULL) {
printf("%d ", current->data);
current = current->next;
}
printf("\n");
}
int main() {
// 创建链表
Node* head = (Node*)malloc(sizeof(Node));
head->data = 1;
Node* node2 = (Node*)malloc(sizeof(Node));
node2->data = 2;
Node* node3 = (Node*)malloc(sizeof(Node));
node3->data = 3;
Node* node4 = (Node*)malloc(sizeof(Node));
node4->data = 4;
head->next = node2;
node2->next = node3;
node3->next = node4;
node4->next = NULL;
// 打印原始链表
printf("原始链表:");
printList(head);
// 反转链表
reverseList(&head);
// 打印反转后的链表
printf("反转后的链表:");
printList(head);
// 释放链表内存
Node* current = head;
Node* next;
while (current != NULL) {
next = current->next;
free(current);
current = next;
}
return 0;
}
运行以上代码,输出结果为:
原始链表:1 2 3 4
反转后的链表:4 3 2 1
可以看到,通过反转链表函数reverseList
,原始链表中的元素顺序被逆转了。