数据结构在链表中插入元素 C语言实现
时间: 2024-02-19 11:03:41 浏览: 21
在链表中插入元素的C语言实现,可以按照以下步骤进行:
1. 创建一个新节点,用于存储要插入的元素。
2. 遍历链表,找到要插入节点的位置。可以使用一个指针指向当前节点,然后依次往下遍历,直到找到插入位置。
3. 将新节点的指针指向当前节点的下一个节点,同时将当前节点的指针指向新节点。
下面是一个简单的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
// 链表节点结构体
struct node {
int data;
struct node *next;
};
// 在链表中插入元素
void insert_node(struct node **head, int data, int index) {
// 创建新节点
struct node *new_node = (struct node *)malloc(sizeof(struct node));
new_node->data = data;
new_node->next = NULL;
// 如果链表为空,直接将新节点作为头节点
if (*head == NULL) {
*head = new_node;
return;
}
// 如果插入位置是头节点之前,直接将新节点作为头节点
if (index <= 0) {
new_node->next = *head;
*head = new_node;
return;
}
// 遍历链表,找到插入位置
struct node *current_node = *head;
int i = 0;
while (i < index - 1 && current_node->next != NULL) {
current_node = current_node->next;
i++;
}
// 如果插入位置超出了链表范围,直接将新节点作为尾节点
if (i < index - 1) {
current_node->next = new_node;
return;
}
// 插入新节点
new_node->next = current_node->next;
current_node->next = new_node;
}
// 打印链表
void print_list(struct node *head) {
printf("List: ");
while (head != NULL) {
printf("%d ", head->data);
head = head->next;
}
printf("\n");
}
int main() {
// 创建链表
struct node *head = NULL;
insert_node(&head, 1, 0);
insert_node(&head, 2, 1);
insert_node(&head, 3, 2);
print_list(head);
// 在链表中插入元素
insert_node(&head, 4, 1);
print_list(head);
return 0;
}
```
输出结果为:
```
List: 1 2 3
List: 1 4 2 3
```