请编写一个函数int list_revert(SLIST_S *listA, SLIST_S *listB),将传入的单向链表listA反转后返回listB,其中SLIST_S定义如下: typedef struct SLIST{ …… struct SIG_LIST *next; }SLIST_S;
时间: 2024-03-23 12:40:25 浏览: 17
好的,我可以为你编写这个函数。下面是代码示例:
```
#include <stdio.h>
#include <stdlib.h>
typedef struct SLIST{
int data;
struct SLIST *next;
}SLIST_S;
int list_revert(SLIST_S *listA, SLIST_S **listB) {
if (listA == NULL) {
return -1;
}
SLIST_S *prev = NULL;
SLIST_S *cur = listA;
SLIST_S *next = NULL;
while (cur != NULL) {
next = cur->next;
cur->next = prev;
prev = cur;
cur = next;
}
*listB = prev;
return 0;
}
int main() {
// 创建单向链表
SLIST_S *head = (SLIST_S *)malloc(sizeof(SLIST_S));
SLIST_S *node1 = (SLIST_S *)malloc(sizeof(SLIST_S));
SLIST_S *node2 = (SLIST_S *)malloc(sizeof(SLIST_S));
SLIST_S *node3 = (SLIST_S *)malloc(sizeof(SLIST_S));
head->data = 1;
node1->data = 2;
node2->data = 3;
node3->data = 4;
head->next = node1;
node1->next = node2;
node2->next = node3;
node3->next = NULL;
// 打印反转前的单向链表
SLIST_S *p = head;
while (p != NULL) {
printf("%d ", p->data);
p = p->next;
}
printf("\n");
// 反转单向链表
SLIST_S *new_head = NULL;
list_revert(head, &new_head);
// 打印反转后的单向链表
p = new_head;
while (p != NULL) {
printf("%d ", p->data);
p = p->next;
}
printf("\n");
return 0;
}
```
函数`list_revert(SLIST_S *listA, SLIST_S **listB)`接受两个参数,第一个参数是要反转的单向链表的头指针`listA`,第二个参数是返回的反转后的单向链表的头指针`listB`的地址。
在函数中,我们使用了三个指针变量`prev`、`cur`和`next`,其中`prev`指向当前节点的前一个节点,`cur`指向当前节点,`next`指向当前节点的后一个节点。我们从头节点开始遍历单向链表,每次将`cur`节点的`next`指针指向`prev`节点,然后将`prev`和`cur`同时向后移动一个节点,直到遍历完整个单向链表,最后将`listB`指向反转后的单向链表的头节点`prev`。
在`main`函数中,我们创建了一个单向链表,然后调用`list_revert`函数将其反转,并打印反转前后的单向链表,以便验证反转是否成功。