用C语言写一个逆序创建链表的代码
时间: 2024-05-27 10:11:22 浏览: 17
#include <stdio.h>
#include <stdlib.h>
// 定义链表节点结构体
typedef struct node {
int data;
struct node *next;
} Node;
// 创建链表函数
Node* createList() {
Node *head = NULL; // 头节点指针初始化为空
int data;
printf("请输入链表数据,以-1结束:");
while (1) {
scanf("%d", &data);
if (data == -1) break; // 输入-1结束输入
Node *newNode = (Node*)malloc(sizeof(Node)); // 创建新节点
newNode->data = data;
newNode->next = head; // 头插法插入新节点
head = newNode; // 将新节点作为头节点
}
return head;
}
// 打印链表函数
void printList(Node *head) {
Node *p = head;
while (p) {
printf("%d ", p->data);
p = p->next;
}
printf("\n");
}
int main() {
Node *head = createList(); // 创建链表
printList(head); // 打印链表
return 0;
}