阅读量:2
要实现C语言双向链表的反转,可以采取以下步骤:
- 定义一个指向链表头部的指针和一个指向链表尾部的指针,分别称为head和tail。
- 遍历链表,将每个节点的prev指针和next指针进行交换。
- 最后,交换head和tail指针。
以下是一个示例代码:
#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字段不存储任何数据,只是用来方便操作。