单链表反转
#include <stdio.h>
#include <stdlib.h>
// 定义链表节点结构
struct Node {
int data;
struct Node* next;
};
// 反转链表函数
struct Node* reverseList(struct Node* head) {
struct Node* prev = NULL;
struct Node* current = head;
struct Node* next = NULL;
while (current != NULL) {
next = current->next; // 保存下一个节点的指针
current->next = prev; // 反转当前节点的指针
prev = current; // 更新 prev 指针
current = next; // 更新 current 指针
}
head = prev; // 更新头指针为新的链表头
return head;
}
// 输出链表内容函数
void printList(struct Node* node) {
while (node != NULL) {
printf("%d ", node->data);
node = node->next;
}
printf("\n");
}
int main() {
struct Node* head = NULL;
struct Node* second = NULL;
struct Node* third = NULL;
// 分配节点内存
head = (struct Node*)malloc(sizeof(struct Node));
second = (struct Node*)malloc(sizeof(struct Node));
third = (struct Node*)malloc(sizeof(struct Node));
// 设置节点数据
head->data = 1;
head->next = second;
second->data = 2;
second->next = third;
third->data = 3;
third->next = NULL;
printf("Original list: \n");
printList(head);
// 反转链表
head = reverseList(head);
printf("Reversed list: \n");
printList(head);
return 0;
}
双链表反转
#include <stdio.h>
#include <stdlib.h>
// 定义双向链表节点结构
struct Node {
int data;
struct Node* next;
struct Node* prev;
};
// 反转双向链表函数
struct Node* reverseDoublyLinkedList(struct Node* head) {
struct Node* temp = NULL;
struct Node* current = head;
// 交换每个节点的 prev 和 next 指针
while (current != NULL) {
temp = current->prev;
current->prev = current->next;
current->next = temp;
current = current->prev; // 移动到下一个节点
}
// 更新头指针为新的链表头
if (temp != NULL) {
head = temp->prev;
}
return head;
}
// 输出双向链表内容函数
void printDoublyList(struct Node* node) {
struct Node* last = NULL;
printf("\n从前往后打印链表:\n");
while (node != NULL) {
printf("%d ", node->data);
last = node;
node = node->next;
}
printf("\n从后往前打印链表:\n");
while (last != NULL) {
printf("%d ", last->data);
last = last->prev;
}
printf("\n");
}
int main() {
struct Node* head = NULL;
struct Node* second = NULL;
struct Node* third = NULL;
// 分配节点内存
head = (struct Node*)malloc(sizeof(struct Node));
second = (struct Node*)malloc(sizeof(struct Node));
third = (struct Node*)malloc(sizeof(struct Node));
// 设置节点数据
head->data = 1;
head->prev = NULL;
head->next = second;
second->data = 2;
second->prev = head;
second->next = third;
third->data = 3;
third->prev = second;
third->next = NULL;
printf("Original list: ");
printDoublyList(head);
// 反转双向链表
head = reverseDoublyLinkedList(head);
printf("Reversed list: ");
printDoublyList(head);
return 0;
}