c语言编写双链表的反转
时间: 2023-03-27 08:02:24 浏览: 91
利用C编程编写链表逆转
可以使用以下代码实现双链表的反转:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node* prev;
struct Node* next;
} Node;
Node* reverse(Node* head) {
Node* current = head;
Node* temp = NULL;
while (current != NULL) {
temp = current->prev;
current->prev = current->next;
current->next = temp;
current = current->prev;
}
if (temp != NULL) {
head = temp->prev;
}
return head;
}
int main() {
Node* head = NULL;
Node* tail = NULL;
for (int i = 1; i <= 5; i++) {
Node* node = (Node*)malloc(sizeof(Node));
node->data = i;
node->prev = tail;
node->next = NULL;
if (tail != NULL) {
tail->next = node;
}
tail = node;
if (head == NULL) {
head = node;
}
}
printf("Original list: ");
Node* current = head;
while (current != NULL) {
printf("%d ", current->data);
current = current->next;
}
head = reverse(head);
printf("\nReversed list: ");
current = head;
while (current != NULL) {
printf("%d ", current->data);
current = current->next;
}
return ;
}
```
阅读全文