c语言实现单链表的插入
时间: 2023-11-25 19:07:21 浏览: 82
以下是c语言实现单链表的插入的代码:
```c
#include <stdio.h>
#include <stdlib.h>
//定义链表节点
typedef struct node {
int data;
struct node *next;
} Node;
//插入节点
void insert(Node **head, int data) {
Node *newNode = (Node*)malloc(sizeof(Node));
newNode->data = data;
newNode->next = NULL;
if (*head == NULL) {
*head = newNode;
} else {
Node *current = *head;
while (current->next != NULL) {
current = current->next;
}
current->next = newNode;
}
}
//输出链表
void printList(Node *head) {
Node *current = head;
while (current != NULL) {
printf("%d ", current->data);
current = current->next;
}
printf("\n");
}
int main() {
Node *head = NULL;
insert(&head, 1);
insert(&head, 2);
insert(&head, 3);
insert(&head, 4);
insert(&head, 5);
printList(head);
return 0;
}
```
在上面的代码中,我们首先定义了一个节点结构体,包含了数据和指向下一个节点的指针。然后定义了插入函数,用于在链表末尾插入节点。如果链表为空,则将新节点作为头节点,否则遍历链表找到最后一个节点,将新节点插入到其后面。最后,定义了一个输出链表的函数,用于打印链表中的所有节点。在主函数中,我们创建了一个空的链表,并插入了一些节点,最后输出整个链表。
阅读全文
相关推荐















