帮我写一个C语言代码,用头插法建立带头结点的单链表
时间: 2024-05-08 09:16:03 浏览: 10
下面是使用头插法建立带头结点的单链表的C语言代码:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node *next;
} Node;
Node *createList() {
Node *head = (Node *)malloc(sizeof(Node));
head->next = NULL;
Node *p;
int x;
printf("请输入链表中的数据,输入-1结束:\n");
scanf("%d", &x);
while (x != -1) {
p = (Node *)malloc(sizeof(Node));
p->data = x;
p->next = head->next;
head->next = p;
scanf("%d", &x);
}
return head;
}
void printList(Node *head) {
Node *p = head->next;
printf("链表中的数据为:");
while (p != NULL) {
printf("%d ", p->data);
p = p->next;
}
printf("\n");
}
int main() {
Node *head = createList();
printList(head);
return 0;
}
```
运行结果:
```
请输入链表中的数据,输入-1结束:
1
2
3
4
5
-1
链表中的数据为:5 4 3 2 1
```