编写不带头结点单链表的插入操作和删除操作算法c语言
时间: 2024-05-05 12:20:16 浏览: 101
插入操作:
```
void insert(Node* &head, int val) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->val = val;
newNode->next = NULL;
if (head == NULL) {
head = newNode;
return;
}
Node* cur = head;
while (cur->next != NULL) {
cur = cur->next;
}
cur->next = newNode;
}
```
删除操作:
```
void delete(Node* &head, int val) {
if (head == NULL) {
return;
}
if (head->val == val) {
Node* temp = head;
head = head->next;
free(temp);
return;
}
Node* cur = head;
while (cur->next != NULL && cur->next->val != val) {
cur = cur->next;
}
if (cur->next != NULL) {
Node* temp = cur->next;
cur->next = cur->next->next;
free(temp);
}
}
```
阅读全文