#include <stdio.h>
#include <stdlib.h>
struct node {
int data;
struct node* next;
};
typedef struct node Node;
Node* createList();
Node* reverseList(Node* head);
void printList(Node* head);
int main() {
Node* head = createList(); // 创建链表
printf("原始链表:");
printList(head); // 输出原始链表
head = reverseList(head); // 链表逆置
printf("逆置链表:");
printList(head); // 输出逆置后的链表
return 0;
}
// 创建链表
Node* createList() {
Node* head = NULL;
Node* tail = NULL;
int num;
printf("请输入正整数,输入-1结束:");
scanf("%d", &num);
while (num != -1) {
Node* p = (Node*)malloc(sizeof(Node));
p->data = num;
p->next = NULL;
if (head == NULL) {
head = p;
tail = p;
}
else {
tail->next = p;
tail = p;
}
scanf("%d", &num);
}
return head;
}
// 链表逆置
Node* reverseList(Node* head) {
if (head == NULL || head->next == NULL) {
return head; // 空链表或只有一个节点,直接返回头节点
}
Node* prev = NULL;
Node* cur = head;
while (cur != NULL) {
Node* next = cur->next;
cur->next = prev;
prev = cur;
cur = next;
}
return prev;
}
// 输出链表
void printList(Node* head) {
while (head != NULL) {
printf("%d ", head->data);
head = head->next;
}
printf("\n");
}
03-31
6385
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
11-18
1万+
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)