创建和输出链表c语言
时间: 2024-04-05 19:25:58 浏览: 24
创建和输出链表的C语言代码如下:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义链表节点结构体
struct Node {
int data;
struct Node* next;
};
// 创建链表
struct Node* createLinkedList(int n) {
struct Node* head = NULL;
struct Node* temp = NULL;
struct Node* p = NULL;
int i;
// 分配内存空间
head = (struct Node*)malloc(sizeof(struct Node));
// 如果内存分配失败
if (head == NULL) {
printf("内存分配失败!\n");
exit(0);
}
// 输入链表的第一个节点的数据
printf("输入节点1的数据:");
scanf("%d", &head->data);
head->next = NULL;
temp = head;
// 输入链表的其他节点的数据
for (i = 2; i <= n; i++) {
p = (struct Node*)malloc(sizeof(struct Node));
if (p == NULL) {
printf("内存分配失败!\n");
exit(0);
}
printf("输入节点%d的数据:", i);
scanf("%d", &p->data);
p->next = NULL;
temp->next = p;
temp = temp->next;
}
return head;
}
// 输出链表
void displayLinkedList(struct Node* head) {
struct Node* p = head;
// 遍历链表并输出每个节点的数据
while (p != NULL) {
printf("%d ", p->data);
p = p->next;
}
printf("\n");
}
int main() {
struct Node* head = NULL;
int n;
printf("输入链表的节点数:");
scanf("%d", &n);
// 创建链表
head = createLinkedList(n);
// 输出链表
printf("链表的元素为:");
displayLinkedList(head);
return 0;
}
```