c语言动态链表的创建
时间: 2023-12-12 17:35:59 浏览: 99
C语言动态链表的创建可以通过以下步骤实现:
1. 定义链表节点结构体,包含数据域和指针域。
2. 定义链表头指针,初始化为NULL。
3. 动态申请内存空间,创建新节点。
4. 将新节点插入链表中。
5. 重复步骤3和4,直到链表创建完成。
下面是一个示例代码,演示了如何动态创建链表:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node* next;
} Node;
Node* createList(int n) {
Node *head, *p, *q;
int i;
head = (Node*)malloc(sizeof(Node));
head->next = NULL;
q = head;
for (i = 0; i < n; i++) {
p = (Node*)malloc(sizeof(Node));
printf("请输入第%d个节点的值:", i + 1);
scanf("%d", &p->data);
p->next = NULL;
q->next = p;
q = p;
}
return head;
}
void printList(Node* head) {
Node* p = head->next;
while (p != NULL) {
printf("%d ", p->data);
p = p->next;
}
printf("\n");
}
int main() {
int n;
Node* head;
printf("请输入链表的长度:");
scanf("%d", &n);
head = createList(n);
printf("创建的链表为:");
printList(head);
return 0;
}
```
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)