用c语言写:请编程序建立一个带有头节点的单向链表,链表节点中的数据通过键盘输入,当输入数据为-1时,表示输入结束(链表头节点的data域不放数据,表空的条件是ph->next==NULL) #include<stdio.h>
时间: 2024-02-01 12:16:56 浏览: 72
链表建立的步骤-C语言单向链表
```
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
int data;
struct node *next;
} Node;
void createList(Node *head) {
Node *p, *q;
p = head;
int num;
printf("请输入数据:");
scanf("%d", &num);
while (num != -1) {
q = (Node*)malloc(sizeof(Node));
q->data = num;
q->next = NULL;
p->next = q;
p = q;
printf("请输入数据:");
scanf("%d", &num);
}
}
void printList(Node *head) {
Node *p = head->next;
while (p) {
printf("%d ", p->data);
p = p->next;
}
printf("\n");
}
int main() {
Node *head = (Node*)malloc(sizeof(Node));
head->next = NULL;
createList(head);
printList(head);
return 0;
}
```
阅读全文