用c语言写尾插法单链表
时间: 2023-03-29 21:02:45 浏览: 62
可以使用以下代码实现尾插法单链表:
```c
#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);
insert(&head, 4);
printf("Created Linked List: ");
printList(head);
return ;
}
```
这段代码实现了一个尾插法单链表,可以通过调用 `insert` 函数来插入新的节点,通过调用 `printList` 函数来打印链表中的所有节点。