编程实现对一个单向链表的结点进行反转,也就是将链表结点按逆序排列,排序后链头将成为链尾,而链尾将成为链头。自定义函数名称及函数功能要求如下: (1)定义“createNode”函数,实现创建一个新结点。 (2)定义“createList”函数,实现一个单向链表的创建。 ● 在创建结点时通过键盘输入为每个结点的数据成员value进行赋值。 ● 使用“头插法”将每个结点逐一插入到链表中。 (3)定义“display”的函数,实现对链表所有结点的遍历输出。 (4)定义“reverse”的函数,实现对链表结点的反转 c语言不用for循环
时间: 2023-12-10 07:37:28 浏览: 32
以下是实现要求的代码:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义链表结点结构体
struct Node {
int value;
struct Node* next;
};
// 创建新结点
struct Node* createNode(int value) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->value = value;
newNode->next = NULL;
return newNode;
}
// 创建链表
struct Node* createList(int n) {
struct Node* head = NULL;
struct Node* temp = NULL;
int value;
for (int i = 0; i < n; i++) {
printf("请输入第 %d 个结点的值: ", i+1);
scanf("%d", &value);
// 创建新结点
struct Node* newNode = createNode(value);
// 头插法插入结点
if (head == NULL) {
head = newNode;
} else {
newNode->next = head;
head = newNode;
}
}
return head;
}
// 遍历链表
void display(struct Node* head) {
printf("链表的所有结点值为: ");
while (head != NULL) {
printf("%d ", head->value);
head = head->next;
}
printf("\n");
}
// 反转链表
struct Node* reverse(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;
}
int main() {
int n;
printf("请输入链表的结点数: ");
scanf("%d", &n);
// 创建链表
struct Node* head = createList(n);
// 遍历链表
display(head);
// 反转链表
struct Node* newHead = reverse(head);
// 遍历反转后的链表
display(newHead);
return 0;
}
```
使用方法:
1. 运行程序
2. 输入链表结点数
3. 依次输入每个结点的值
4. 程序将创建并输出原始链表
5. 程序将反转链表并输出反转后的链表
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![java](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![md](https://img-home.csdnimg.cn/images/20210720083646.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)