用c语言编写一个代码,用头插法创建头指针单链表,并打印,
时间: 2023-05-27 21:06:25 浏览: 105
c语言:创建单链表的头插法代码
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node *next;
} Node, *LinkList;
LinkList createList(int n);
void printList(LinkList list);
int main() {
int n;
printf("请输入链表的长度:");
scanf("%d", &n);
LinkList list = createList(n);
printf("创建的链表为:");
printList(list);
return 0;
}
LinkList createList(int n) {
LinkList list = (LinkList) malloc(sizeof(Node));
list->next = NULL;
for (int i = 0; i < n; i++) {
Node *node = (Node *) malloc(sizeof(Node));
printf("请输入第%d个节点的值:", i + 1);
scanf("%d", &(node->data));
node->next = list->next;
list->next = node;
}
return list;
}
void printList(LinkList list) {
Node *p = list->next;
while (p != NULL) {
printf("%d ", p->data);
p = p->next;
}
printf("\n");
}
阅读全文