1、 已知带头结点的单链表L={a1,a2,...an},试编写一个算法,将L中的元素进行逆置,即L ={an,an-1,...a1}c语言实现
时间: 2024-02-09 17:09:11 浏览: 164
以下是基于C语言的算法实现:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
int data;
struct node *next;
} ListNode, *LinkedList;
LinkedList create_linked_list(int n) {
LinkedList head = (LinkedList) malloc(sizeof(ListNode));
head->next = NULL;
ListNode *tail = head;
int i, value;
for (i = 0; i < n; i++) {
scanf("%d", &value);
ListNode *p = (ListNode *) malloc(sizeof(ListNode));
p->data = value;
p->next = NULL;
tail->next = p;
tail = p;
}
return head;
}
LinkedList reverse_linked_list(LinkedList head) {
ListNode *pre_node = NULL;
ListNode *cur_node = head->next;
while (cur_node != NULL) {
ListNode *next_node = cur_node->next;
cur_node->next = pre_node;
pre_node = cur_node;
cur_node = next_node;
}
head->next = pre_node;
return head;
}
void print_linked_list(LinkedList head) {
ListNode *p = head->next;
while (p != NULL) {
printf("%d ", p->data);
p = p->next;
}
printf("\n");
}
int main() {
int n;
printf("Please enter the number of nodes: ");
scanf("%d", &n);
printf("Please enter the values of nodes: ");
LinkedList L = create_linked_list(n);
printf("Original linked list: ");
print_linked_list(L);
L = reverse_linked_list(L);
printf("Reversed linked list: ");
print_linked_list(L);
return 0;
}
```
算法思路:
1. 定义一个结构体 `ListNode` 表示链表节点,其中包含一个 `int` 类型的数据域 `data` 和一个指向下一个节点的指针 `next`;
2. 定义 `LinkedList` 类型表示带头结点的单链表,其中包含一个指向头结点的指针 `head`;
3. 定义函数 `create_linked_list` 创建带头结点的单链表,其中参数 `n` 表示链表中节点的个数;
4. 定义函数 `reverse_linked_list` 将带头结点的单链表逆置,其中参数 `head` 表示链表的头结点;
5. 定义函数 `print_linked_list` 输出带头结点的单链表中各节点的值,其中参数 `head` 表示链表的头结点;
6. 在 `main` 函数中,首先读入链表中节点的个数 `n` 和各节点的值,然后调用 `create_linked_list` 函数创建带头结点的单链表;
7. 输出原始链表中各节点的值,调用 `reverse_linked_list` 函数将链表逆置,输出逆置后链表中各节点的值;
8. 释放链表中各节点的内存空间。
这样就可以将链表逆置。
阅读全文
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![text/x-c](https://img-home.csdnimg.cn/images/20250102104920.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![](https://img-home.csdnimg.cn/images/20250102104920.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.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)
![text/x-c](https://img-home.csdnimg.cn/images/20250102104920.png)