要實(shí)現(xiàn)單鏈表的反轉(zhuǎn),可以按照以下步驟進(jìn)行:
下面是使用C語言實(shí)現(xiàn)單鏈表反轉(zhuǎn)的代碼示例:
#include <stdio.h>
#include <stdlib.h>
// 定義鏈表節(jié)點(diǎn)結(jié)構(gòu)體
typedef struct Node {
int data;
struct Node* next;
} Node;
// 定義鏈表反轉(zhuǎn)函數(shù)
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;
}
// 定義鏈表打印函數(shù)
void printList(Node* head) {
Node* current = head;
while (current != NULL) {
printf("%d ", current->data);
current = current->next;
}
printf("\n");
}
int main() {
// 創(chuàng)建鏈表
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);
// 反轉(zhuǎn)鏈表
reverseList(&head);
// 打印反轉(zhuǎn)后的鏈表
printf("反轉(zhuǎn)后的鏈表:");
printList(head);
// 釋放鏈表內(nèi)存
Node* current = head;
Node* next;
while (current != NULL) {
next = current->next;
free(current);
current = next;
}
return 0;
}
運(yùn)行以上代碼,輸出結(jié)果為:
原始鏈表:1 2 3 4
反轉(zhuǎn)后的鏈表:4 3 2 1
可以看到,通過反轉(zhuǎn)鏈表函數(shù)reverseList
,原始鏈表中的元素順序被逆轉(zhuǎn)了。