用C语言写出一个采用单链表存储的线性表A(A带表头结点 Head)的数据元素逆置的算法。
时间: 2023-04-08 07:01:32 浏览: 71
可以的,以下是C语言的代码实现:
```
void ReverseList(LinkList A) {
if (A == NULL || A->next == NULL) {
return;
}
ListNode *p = A->next;
ListNode *q = p->next;
A->next = NULL;
while (q != NULL) {
p->next = A->next;
A->next = p;
p = q;
q = q->next;
}
p->next = A->next;
A->next = p;
}
```
这个算法可以将链表A中的数据元素逆置。
相关问题
写出一个采用单链表存储的线性表A(A带表头结点 Head)的数据元素逆置的C语言程序
以下是采用单链表存储的线性表A的数据元素逆置的C语言程序:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node *next;
} Node;
void reverseList(Node *head) {
Node *p = head->next;
Node *q = NULL;
head->next = NULL;
while (p != NULL) {
q = p->next;
p->next = head->next;
head->next = p;
p = q;
}
}
int main() {
Node *head = (Node *) malloc(sizeof(Node));
head->next = NULL;
int n, x;
printf("请输入线性表A的长度:");
scanf("%d", &n);
printf("请输入线性表A的元素:");
for (int i = 0; i < n; i++) {
scanf("%d", &x);
Node *p = (Node *) malloc(sizeof(Node));
p->data = x;
p->next = head->next;
head->next = p;
}
printf("逆置前线性表A的元素为:");
Node *p = head->next;
while (p != NULL) {
printf("%d ", p->data);
p = p->next;
}
printf("\n");
reverseList(head);
printf("逆置后线性表A的元素为:");
p = head->next;
while (p != NULL) {
printf("%d ", p->data);
p = p->next;
}
printf("\n");
return 0;
}
```
该程序中,reverseList函数实现了线性表A的数据元素逆置,main函数中先输入线性表A的长度和元素,然后输出逆置前的线性表A的元素,调用reverseList函数逆置线性表A的元素,最后输出逆置后的线性表A的元素。
写出一个采用单链表存储的线性表A(A带表头结点Head)的数据元素逆置的算法)
可以使用三个指针分别指向当前节点、前一个节点和后一个节点,依次遍历链表并将当前节点的指针指向前一个节点,直到遍历完整个链表。具体实现如下:
```
void reverseList(ListNode* head) {
if (head == NULL || head->next == NULL) {
return;
}
ListNode* prev = NULL;
ListNode* curr = head->next;
ListNode* next = NULL;
while (curr != NULL) {
next = curr->next;
curr->next = prev;
prev = curr;
curr = next;
}
head->next = prev;
}
```
其中,ListNode 是链表节点的结构体,包含一个 val 值和一个指向下一个节点的指针 next。
相关推荐
![cpp](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)