要實現C語言雙向鏈表的反轉,可以采取以下步驟:
以下是一個示例代碼:
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node* prev;
struct Node* next;
} Node;
// 創建鏈表
Node* createLinkedList(int n) {
Node *head, *p, *newNode;
int i, data;
head = (Node*)malloc(sizeof(Node));
head->prev = NULL;
head->next = NULL;
p = head;
for (i = 0; i < n; i++) {
newNode = (Node*)malloc(sizeof(Node));
printf("輸入第 %d 個節點的值: ", i+1);
scanf("%d", &data);
newNode->data = data;
newNode->prev = p;
newNode->next = NULL;
p->next = newNode;
p = p->next;
}
return head;
}
// 反轉鏈表
Node* reverseLinkedList(Node* head) {
Node* temp = NULL;
Node* current = head;
// 遍歷鏈表并交換prev和next指針
while (current != NULL) {
temp = current->prev;
current->prev = current->next;
current->next = temp;
current = current->prev;
}
// 更新head指針
if (temp != NULL) {
head = temp->prev;
}
return head;
}
// 打印鏈表
void printLinkedList(Node* head) {
Node* current = head->next;
while (current != NULL) {
printf("%d ", current->data);
current = current->next;
}
printf("\n");
}
int main() {
int n;
Node* head;
printf("輸入鏈表長度: ");
scanf("%d", &n);
head = createLinkedList(n);
printf("原始鏈表: ");
printLinkedList(head);
head = reverseLinkedList(head);
printf("反轉后的鏈表: ");
printLinkedList(head);
return 0;
}
注意:在這個示例代碼中,我們使用了一個帶有頭結點的雙向鏈表,頭結點的data字段不存儲任何數據,只是用來方便操作。