要实现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字段不存储任何数据,只是用来方便操作。