双向链表反转c语言
时间: 2023-07-03 17:24:23 浏览: 75
以下是双向链表反转的 C 语言代码:
```c
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* next;
struct Node* prev;
};
void printList(struct Node* node) {
while (node != NULL) {
printf("%d ", node->data);
node = node->next;
}
printf("\n");
}
void reverseList(struct Node** head) {
struct Node* temp = NULL;
struct Node* current = *head;
while (current != NULL) {
temp = current->prev;
current->prev = current->next;
current->next = temp;
current = current->prev;
}
if (temp != NULL) {
*head = temp->prev;
}
}
int main() {
struct Node* head = NULL;
struct Node* first = (struct Node*)malloc(sizeof(struct Node));
struct Node* second = (struct Node*)malloc(sizeof(struct Node));
struct Node* third = (struct Node*)malloc(sizeof(struct Node));
first->data = 1;
first->prev = NULL;
first->next = second;
second->data = 2;
second->prev = first;
second->next = third;
third->data = 3;
third->prev = second;
third->next = NULL;
head = first;
printf("Original List: ");
printList(head);
reverseList(&head);
printf("Reversed List: ");
printList(head);
return 0;
}
```
在这个代码中,我们定义了一个 `Node` 结构体,包含了数据、前驱指针和后继指针。`printList` 函数用于打印链表中的每个元素。`reverseList` 函数用于反转链表,该函数的参数是一个指向指针的指针,因为我们需要在函数内部改变链表头指针的值。
在 `reverseList` 函数中,我们使用 `temp` 变量来保存当前结点的前驱指针,因为我们需要在交换当前结点的前驱和后继指针后,把它赋给下一个结点的前驱指针。最后,我们需要更新链表头指针的值,否则我们会得到一个不完整的链表。
在 `main` 函数中,我们创建了一个简单的双向链表,并将其传递给 `reverseList` 函数来反转它。最后,我们使用 `printList` 函数来检查链表是否被正确地反转。