单链表的插入和删除代码
时间: 2023-11-05 18:04:33 浏览: 82
单链表的插入与删除
单链表的插入和删除代码可以通过以下方式实现:
插入代码:
```
struct Node {
int data;
Node* next;
};
void insert(Node* head, int val) {
Node* newNode = new Node();
newNode->data = val;
newNode->next = NULL;
Node* cur = head;
while (cur->next != NULL) {
cur = cur->next;
}
cur->next = newNode;
}
```
删除代码:
```
void delete(Node* head, int val) {
Node* cur = head;
Node* pre;
while (cur != NULL && cur->data != val) {
pre = cur;
cur = cur->next;
}
if (cur == NULL) return;
pre->next = cur->next;
delete cur;
}
```
希望我的代码能够帮到你。
阅读全文