是单向链表的 C 语言实现
时间: 2024-05-16 14:15:07 浏览: 12
好的,以下是一个简单的单向链表的 C 语言实现:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义链表结构体
struct Node {
int data; // 存储数据
struct Node* next; // 指向下一个节点的指针
};
// 创建新节点
struct Node* create_node(int data) {
struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));
new_node->data = data;
new_node->next = NULL;
return new_node;
}
// 在链表尾部插入节点
void append_node(struct Node** head, int data) {
struct Node* new_node = create_node(data);
if (*head == NULL) {
*head = new_node;
return;
}
struct Node* temp = *head;
while (temp->next != NULL) {
temp = temp->next;
}
temp->next = new_node;
}
// 在链表中间插入节点
void insert_node(struct Node** head, int data, int position) {
struct Node* new_node = create_node(data);
if (position == 1) {
new_node->next = *head;
*head = new_node;
return;
}
struct Node* temp = *head;
for (int i = 1; i < position - 1; i++) {
if (temp == NULL) {
printf("Invalid position\n");
return;
}
temp = temp->next;
}
new_node->next = temp->next;
temp->next = new_node;
}
// 删除节点
void delete_node(struct Node** head, int position) {
if (*head == NULL) {
printf("List is empty\n");
return;
}
struct Node* temp = *head;
if (position == 1) {
*head = temp->next;
free(temp);
return;
}
for (int i = 1; i < position - 1; i++) {
if (temp == NULL) {
printf("Invalid position\n");
return;
}
temp = temp->next;
}
if (temp == NULL || temp->next == NULL) {
printf("Invalid position\n");
return;
}
struct Node* next_node = temp->next->next;
free(temp->next);
temp->next = next_node;
}
// 打印链表
void print_list(struct Node* head) {
struct Node* temp = head;
while (temp != NULL) {
printf("%d ", temp->data);
temp = temp->next;
}
printf("\n");
}
int main() {
struct Node* head = NULL;
append_node(&head, 1);
append_node(&head, 2);
append_node(&head, 3);
append_node(&head, 4);
print_list(head);
insert_node(&head, 5, 3);
print_list(head);
delete_node(&head, 2);
print_list(head);
delete_node(&head, 5);
print_list(head);
delete_node(&head, 3);
print_list(head);
return 0;
}
```
这个实现包含了创建节点、在链表尾部插入节点、在链表中间插入节点、删除节点以及打印链表等基本操作。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)