C语言数据结构实现链表逆序并输出
作者:野牛程序员:2023-12-22 09:35:40C语言阅读 2760
链表逆序并输出的C语言代码如下:
#include <stdio.h>
#include <stdlib.h>
// 定义链表节点
struct Node {
int data;
struct Node* next;
};
// 函数声明
struct Node* reverseList(struct Node* head);
void printList(struct Node* head);
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;
printf("原始链表: ");
printList(head);
// 反转链表
head = reverseList(head);
printf("逆序后的链表: ");
printList(head);
// 释放内存
free(head);
free(second);
free(third);
return 0;
}
// 反转链表
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;
}
// 输出链表
void printList(struct Node* head) {
struct Node* temp = head;
while (temp != NULL) {
printf("%d ", temp->data);
temp = temp->next;
}
printf("\\n");
}这段代码定义了一个简单的链表结构,然后使用 reverseList 函数来逆序链表,最后使用 printList 函数输出链表。
野牛程序员教少儿编程与信息学奥赛-微信|电话:15892516892

