用c语言写一个构造链表程序
时间: 2023-05-18 11:06:51 浏览: 109
c语言中的链表-用结构体和指针构造链表
5星 · 资源好评率100%
好的,以下是一个简单的用 C 语言编写的构造链表程序:
```c
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* next;
};
struct Node* createNode(int data) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = data;
newNode->next = NULL;
return newNode;
}
void insertNode(struct Node** head, int data) {
struct Node* newNode = createNode(data);
if (*head == NULL) {
*head = newNode;
return;
}
struct Node* current = *head;
while (current->next != NULL) {
current = current->next;
}
current->next = newNode;
}
void printList(struct Node* head) {
struct Node* current = head;
while (current != NULL) {
printf("%d ", current->data);
current = current->next;
}
}
int main() {
struct Node* head = NULL;
insertNode(&head, 1);
insertNode(&head, 2);
insertNode(&head, 3);
insertNode(&head, 4);
insertNode(&head, 5);
printList(head);
return 0;
}
```
这个程序创建了一个链表,插入了 5 个节点,然后打印出链表中的所有节点的数据。
阅读全文