原地反转
#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* curr = head;
struct Node* next = NULL;
while (curr != NULL) {
next = curr->next;
curr->next = prev;
prev = curr;
curr = next;
}
return prev;
}
// 定义链表打印函数
void printList(struct Node* head) {
struct Node* curr = head;
while (curr != NULL) {
printf("%d ", curr->data);
curr = curr->next;
}
printf("\n");
}
int main() {
// 创建链表
struct Node* head = (struct Node*)malloc(sizeof(struct Node));
head->data = 1;
struct Node* node1 = (struct Node*)malloc(sizeof(struct Node));
node1->data = 2;
struct Node* node2 = (struct Node*)malloc(sizeof(struct Node));
node2->data = 3;
head->next = node1;
node1->next = node2;
node2->next = NULL;
// 打印原始链表
printf("原始链表:");
printList(head);
// 反转链表
head = reverseList(head);
// 打印反转后的链表
printf("反转后的链表:");
printList(head);
return 0;
}
该代码中,我们首先定义了一个链表节点结构体 Node,包含一个整型数据 data 和一个指向下一个节点的指针 next。然后,我们定义了一个 reverseList 函数,用于反转链表。该函数使用三个指针 prev、curr 和 next,分别指向当前节点的前一个节点、当前节点和当前节点的下一个节点。在循环中,我们不断将当前节点的 next 指针指向前一个节点,然后将三个指针向后移动。最后,我们返回反转后的链表的头节点。
在 main 函数中,我们创建了一个包含三个节点的链表,并打印了原始链表。然后,我们调用 reverseList 函数反转链表,并打印反转后的链表。
用栈反转
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node* next;
} Node;
void push(Node** top, int data) {
Node* new_node = (Node*)malloc(sizeof(Node));
new_node->data = data;
new_node->next = *top;
*top = new_node;
}
int pop(Node** top) {
if (*top == NULL) {
printf("栈为空\n");
return -1;
}
int data = (*top)->data;
Node* temp = *top;
*top = (*top)->next;
free(temp);
return data;
}
void reverse(Node** head) {
Node* temp = *head;
Node* stack_top = NULL;
while (temp != NULL) {
push(&stack_top, temp->data);
temp = temp->next;
}
temp = *head;
while (temp != NULL) {
temp->data = pop(&stack_top);
temp = temp->next;
}
}
void print_list(Node* head) {
while (head != NULL) {
printf("%d ", head->data);
head = head->next;
}
printf("\n");
}
int main() {
Node* head = (Node*)malloc(sizeof(Node));
head->data = 1;
head->next = (Node*)malloc(sizeof(Node));
head->next->data = 2;
head->next->next = (Node*)malloc(sizeof(Node));
head->next->next->data = 3;
head->next->next->next = NULL;
printf("反转前:");
print_list(head);
reverse(&head);
printf("反转后:");
print_list(head);
return 0;
}
在这个实现中,我们使用了一个栈来存储链表中的元素。首先,我们遍历链表并将每个元素压入栈中。然后,我们再次遍历链表并将栈中的元素弹出并赋值给链表中的每个节点。这样就完成了链表的反转。