c++语言编写一个函数creat,用来建立一个动态链表。所谓建立动态链表是指在程序执行过程中从无到有地建立起一个链表,即一个一个地开辟结点和输人各结点数据,并建立起前后相连的关系。各结点的数据由键盘输入。
时间: 2024-06-04 08:10:59 浏览: 70
#include <stdio.h>
#include <stdlib.h>
struct node {
int data;
struct node *next;
};
struct node *create() {
struct node *head = NULL;
struct node *tail = NULL;
int num;
printf("Enter data for nodes, enter -1 to end:\n");
scanf("%d", &num);
while (num != -1) {
struct node *new_node = (struct node *)malloc(sizeof(struct node));
new_node->data = num;
new_node->next = NULL;
if (head == NULL) {
head = new_node;
tail = new_node;
} else {
tail->next = new_node;
tail = new_node;
}
scanf("%d", &num);
}
return head;
}
int main() {
struct node *head = create();
printf("List: ");
while (head != NULL) {
printf("%d ", head->data);
head = head->next;
}
printf("\n");
return 0;
}
阅读全文