class ListNode { public: ListNode(int x) : val(x), next(NULL) {} int val; ListNode *next; };请根据这个结构体,给出该链表增删改查的代码
时间: 2024-05-25 17:19:32 浏览: 14
链表的增删改查代码如下:
// 增加节点
void addNode(ListNode* &head, int x) {
ListNode* newNode = new ListNode(x);
if (head == NULL) {
head = newNode;
} else {
ListNode* cur = head;
while (cur->next != NULL) {
cur = cur->next;
}
cur->next = newNode;
}
}
// 删除节点
void deleteNode(ListNode* &head, int x) {
ListNode* cur = head;
ListNode* pre = NULL;
while (cur != NULL) {
if (cur->val == x) {
if (pre == NULL) {
head = cur->next;
} else {
pre->next = cur->next;
}
delete cur;
return;
}
pre = cur;
cur = cur->next;
}
}
// 修改节点
void modifyNode(ListNode* &head, int x, int y) {
ListNode* cur = head;
while (cur != NULL) {
if (cur->val == x) {
cur->val = y;
return;
}
cur = cur->next;
}
}
// 查找节点
ListNode* searchNode(ListNode* head, int x) {
ListNode* cur = head;
while (cur != NULL) {
if (cur->val == x) {
return cur;
}
cur = cur->next;
}
return NULL;
}
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)