要實現單鏈表的反轉,可以按照以下步驟進行:
下面是使用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
,原始鏈表中的元素順序被逆轉了。