帮我写一段链表基本操作的c++代码
时间: 2023-06-06 11:07:06 浏览: 61
好的,下面是链表基本操作的 C 代码:
```c
#include <stdio.h>
#include <stdlib.h>
// 链表节点结构体
typedef struct Node {
int data; // 数据域
struct Node *next; // 指针域
} Node;
// 链表头指针
Node *head = NULL;
// 在链表末尾添加节点
void append(int new_data) {
Node *new_node = (Node*) malloc(sizeof(Node));
new_node->data = new_data;
new_node->next = NULL;
if (head == NULL) {
head = new_node;
}
else {
Node *last_node = head;
while (last_node->next != NULL) {
last_node = last_node->next;
}
last_node->next = new_node;
}
}
// 在链表中间插入节点
void insert(Node *prev_node, int new_data) {
if (prev_node == NULL) {
printf("Error: the previous node cannot be NULL.\n");
return;
}
Node *new_node = (Node*) malloc(sizeof(Node));
new_node->data = new_data;
new_node->next = prev_node->next;
prev_node->next = new_node;
}
// 删除链表中的节点
void delete(int key) {
Node *cur_node = head;
Node *prev_node = NULL;
while (cur_node != NULL && cur_node->data != key) {
prev_node = cur_node;
cur_node = cur_node->next;
}
if (cur_node == NULL) {
printf("Error: there is no node with data %d.\n", key);
return;
}
if (prev_node == NULL) {
head = cur_node->next;
}
else {
prev_node->next = cur_node->next;
}
free(cur_node);
}
// 遍历整个链表
void print_list() {
Node *cur_node = head;
while (cur_node != NULL) {
printf("%d -> ", cur_node->data);
cur_node = cur_node->next;
}
printf("NULL\n");
}
int main() {
append(1);
append(2);
append(3);
insert(head, 4);
print_list();
delete(2);
print_list();
return 0;
}
```
希望这段代码对你有帮助!
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)