本题目要求编写一个实现带头结点单链表就地逆置的一个程序。在编写该程序时,要求单独写一个函数来实现单链表的逆置,并编写代码在main函数测试结果。
时间: 2024-05-05 20:19:15 浏览: 164
好的,我明白您的问题了。下面是程序代码:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node* next;
} Node;
void printList(Node* head) {
Node* cur = head->next;
while (cur != NULL) {
printf("%d ", cur->data);
cur = cur->next;
}
printf("\n");
}
void reverseList(Node* head) {
Node* pre = head->next;
Node* cur = pre->next;
Node* next = cur->next;
pre->next = NULL;
while (next != NULL) {
cur->next = pre;
pre = cur;
cur = next;
next = next->next;
}
cur->next = pre;
head->next = cur;
}
int main() {
Node* head = (Node*)malloc(sizeof(Node));
head->next = NULL;
// 创建带头结点单链表
Node* p = head;
for (int i = 1; i <= 5; i++) {
Node* node = (Node*)malloc(sizeof(Node));
node->data = i;
node->next = NULL;
p->next = node;
p = node;
}
// 输出初始链表
printf("初始链表:");
printList(head);
// 链表逆置
reverseList(head);
// 输出逆置后链表
printf("逆置后链表:");
printList(head);
return 0;
}
```
运行结果:
```
初始链表:1 2 3 4 5
逆置后链表:5 4 3 2 1
```
阅读全文
相关推荐















