用C语言写一段链表逆序代码
时间: 2024-01-29 09:04:47 浏览: 87
利用C编程编写链表逆转
好的,这里是使用C语言编写链表逆序的代码:
```
/* 定义链表节点结构体 */
struct Node {
int data;
struct Node* next;
};
/* 定义链表逆序函数 */
struct Node* reverseList(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() {
/* 创建链表 */
struct Node node1 = {1, NULL};
struct Node node2 = {2, NULL};
struct Node node3 = {3, NULL};
node1.next = &node2;
node2.next = &node3;
/* 打印原链表 */
printf("原链表:\n");
struct Node* curr = &node1;
while (curr != NULL) {
printf("%d ", curr->data);
curr = curr->next;
}
/* 逆序链表 */
struct Node* newHead = reverseList(&node1);
/* 打印逆序后的链表 */
printf("\n逆序后的链表:\n");
curr = newHead;
while (curr != NULL) {
printf("%d ", curr->data);
curr = curr->next;
}
return 0;
}
```
希望这段代码能够帮到你!如果有其他问题,欢迎继续问我哦~
阅读全文