编写函数,创建一个10个元素的线性链接表
时间: 2023-05-11 21:06:44 浏览: 61
好的,以下是创建一个10个元素的线性链接表的函数示例:
```c
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* next;
};
struct Node* createLinkedList(int n) {
struct Node *head = NULL, *temp = NULL, *newNode = NULL;
int i;
for (i = 1; i <= n; i++) {
newNode = (struct Node*)malloc(sizeof(struct Node));
if (newNode == NULL) {
printf("Memory allocation failed!\n");
exit(0);
}
printf("Enter the data for node %d: ", i);
scanf("%d", &newNode->data);
newNode->next = NULL;
if (head == NULL) {
head = newNode;
temp = newNode;
} else {
temp->next = newNode;
temp = newNode;
}
}
return head;
}
int main() {
int n = 10;
struct Node* head = createLinkedList(n);
struct Node* temp = head;
printf("\nData entered in the list: ");
while (temp != NULL) {
printf("%d ", temp->data);
temp = temp->next;
}
return 0;
}
```
这个函数会提示用户输入10个整数,然后创建一个包含这些整数的线性链接表,并返回表头节点的指针。在主函数中,我们可以使用这个函数来创建一个10个元素的线性链接表,并打印出表中的数据。