c++中链表的使用方法
时间: 2023-05-30 11:01:50 浏览: 78
在 C 中,链表的使用方法如下:
1. 定义一个链表节点结构体
```c
struct ListNode {
int val;
struct ListNode *next;
};
```
2. 创建链表节点
```c
struct ListNode *newNode(int val) {
struct ListNode *node = (struct ListNode *)malloc(sizeof(struct ListNode));
node->val = val;
node->next = NULL;
return node;
}
```
3. 插入节点
```c
void insertNode(struct ListNode **head, int val) {
struct ListNode *node = newNode(val);
if (*head == NULL) {
*head = node;
} else {
struct ListNode *cur = *head;
while (cur->next != NULL) {
cur = cur->next;
}
cur->next = node;
}
}
```
4. 删除节点
```c
void deleteNode(struct ListNode **head, int val) {
struct ListNode *cur = *head;
struct ListNode *pre = NULL;
while (cur != NULL) {
if (cur->val == val) {
if (pre == NULL) {
*head = cur->next;
} else {
pre->next = cur->next;
}
free(cur);
return;
}
pre = cur;
cur = cur->next;
}
}
```
5. 遍历链表
```c
void traverseList(struct ListNode *head) {
struct ListNode *cur = head;
while (cur != NULL) {
printf("%d ", cur->val);
cur = cur->next;
}
}
```
6. 释放链表
```c
void freeList(struct ListNode *head) {
struct ListNode *cur = head;
while (cur != NULL) {
struct ListNode *tmp = cur;
cur = cur->next;
free(tmp);
}
}
```
以上是链表的基本操作方法,可以根据需要进行修改和扩展。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)