用尾插法创建一个单链表\
时间: 2023-05-19 20:00:45 浏览: 45
非常好的问题!以下是用尾插法创建单链表的示例代码:
```
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* next;
};
void insert(struct Node** head_ref, int new_data) {
struct Node* new_node = (struct Node*) malloc(sizeof(struct Node));
struct Node* last = *head_ref;
new_node->data = new_data;
new_node->next = NULL;
if (*head_ref == NULL) {
*head_ref = new_node;
return;
}
while (last->next != NULL) {
last = last->next;
}
last->next = new_node;
return;
}
void printList(struct Node* node) {
while (node != NULL) {
printf("%d ", node->data);
node = node->next;
}
}
int main() {
struct Node* head = NULL;
insert(&head, 1);
insert(&head, 2);
insert(&head, 3);
printf("Created Linked List: ");
printList(head);
return 0;
}
```
这段代码使用了一个指向指针的指针来传递头指针,这样可以在函数中修改头指针的值。在 insert 函数中,我们首先创建一个新节点,然后遍历链表找到最后一个节点,最后将新节点插入到链表的末尾。在 main 函数中,我们创建一个空链表,然后插入三个节点,最后打印整个链表。