在C语言中,可以通过指针操作来反转一个链表。 首先,需要定义一个结构体表示链表的节点,结构体中包含存储的值(可以是任何类型)和一个指
首先,需要定义一个结构体表示链表的节点,结构体中包含存储的值(可以是任何类型)和一个指向下一个节点的指针。
struct node {
int data;
struct Node* next;
};
然后,可以编写一个函数来反转链表。该函数需要接收链表的头节点作为参数,然后通过指针操作重新排列链表节点的顺序。
struct Node* reverseList(struct Node* head) {
struct Node* prev = NULL;
struct Node* current = head;
struct Node* next = NULL;
while (current != NULL) {
next = current->next;
current->next = prev;
prev = current;
current = next;
}
head = prev;
return head;
}
这个函数使用了三个指针:`prev`用于保存当前节点的前一个节点,`current`用于保存当前节点,`next`用于保存当前节点的下一个节点。在循环中,首先将`next`指针指向当前节点的下一个节点,然后将当前节点的`next`指针指向前一个节点,接着将`prev`指针指向当前节点,将`current`指针指向`next`节点。最后,将头节点指向反转后的链表的最后一个节点。
以下是一个使用反转链表函数的例子:
int main() {
struct Node* head = NULL;
struct Node* second = NULL;
struct Node* third = NULL;
// 创建链表
head = (struct Node*)malloc(sizeof(struct Node));
second = (struct Node*)malloc(sizeof(struct Node));
third = (struct Node*)malloc(sizeof(struct Node));
head->data = 1;
head->next = second;
second->data = 2;
second->next = third;
third->data = 3;
third->next = NULL;
// 反转链表
head = reverseList(head);
// 打印反转后的链表
struct Node* current = head;
while (current != NULL) {
printf("%d ", current->data);
current = current->next;
}
return 0;
}
输出结果为:3 2 1,表示链表已成功反转。
--结束END--
本文标题: C语言反转列表的方法是什么
本文链接: https://www.lsjlt.com/news/470477.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-03-01
2024-03-01
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0