要反轉(zhuǎn)一個(gè)單向鏈表,可以使用三個(gè)指針分別指向當(dāng)前節(jié)點(diǎn)、前一個(gè)節(jié)點(diǎn)和后一個(gè)節(jié)點(diǎn)。然后,通過修改指針的指向來實(shí)現(xiàn)鏈表的反轉(zhuǎn)。
具體步驟如下:
下面是一個(gè)示例代碼實(shí)現(xiàn):
#include<stdio.h>
#include<stdlib.h>
// 定義鏈表節(jié)點(diǎn)結(jié)構(gòu)體
struct Node {
int data;
struct Node* next;
};
// 反轉(zhuǎn)鏈表函數(shù)
struct Node* reverseLinkedList(struct Node* head) {
struct Node* cur = head;
struct Node* prev = NULL;
struct Node* next = NULL;
while (cur != NULL) {
next = cur->next; // 暫存當(dāng)前節(jié)點(diǎn)的下一個(gè)節(jié)點(diǎn)
cur->next = prev; // 將當(dāng)前節(jié)點(diǎn)的下一個(gè)節(jié)點(diǎn)指向前一個(gè)節(jié)點(diǎn),實(shí)現(xiàn)翻轉(zhuǎn)
prev = cur; // 前一個(gè)節(jié)點(diǎn)指針后移
cur = next; // 當(dāng)前節(jié)點(diǎn)指針后移
}
head = prev; // 將鏈表頭節(jié)點(diǎn)指向翻轉(zhuǎn)后的鏈表的頭節(jié)點(diǎn)
return head;
}
// 打印鏈表函數(shù)
void printLinkedList(struct Node* head) {
struct Node* cur = head;
while (cur != NULL) {
printf("%d ", cur->data);
cur = cur->next;
}
printf("\n");
}
int main() {
// 創(chuàng)建鏈表
struct Node* head = (struct Node*)malloc(sizeof(struct Node));
struct Node* second = (struct Node*)malloc(sizeof(struct Node));
struct Node* third = (struct Node*)malloc(sizeof(struct Node));
head->data = 1;
head->next = second;
second->data = 2;
second->next = third;
third->data = 3;
third->next = NULL;
printf("原始鏈表:");
printLinkedList(head);
// 反轉(zhuǎn)鏈表
head = reverseLinkedList(head);
printf("反轉(zhuǎn)后的鏈表:");
printLinkedList(head);
// 釋放內(nèi)存
free(head);
free(second);
free(third);
return 0;
}
以上代碼創(chuàng)建了一個(gè)包含3個(gè)節(jié)點(diǎn)的鏈表,然后調(diào)用reverseLinkedList
函數(shù)來反轉(zhuǎn)鏈表,并使用printLinkedList
函數(shù)打印結(jié)果。最后釋放動(dòng)態(tài)分配的內(nèi)存。
輸出結(jié)果如下:
原始鏈表:1 2 3
反轉(zhuǎn)后的鏈表:3 2 1