请你实现一个链表; 操作: insert x y:将 y 加入链表,插入在第一个值为 x 的结点之前。若链表中不存在 值为 x 的结点,则插入在链表末尾。保证 x,y 为 int 型整数。 delete x:删除链表中第一个值为 x 的结点。若不存在值为 x 的结点,则不删除的c语言代码
时间: 2023-05-17 12:07:44 浏览: 143
以下是实现一个链表的 C 语言代码:
```c
#include <stdio.h>
#include <stdlib.h>
struct Node {
int val;
struct Node* next;
};
struct Node* head = NULL;
void insert(int x, int y) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->val = y;
newNode->next = NULL;
if (head == NULL) {
head = newNode;
return;
}
struct Node* cur = head;
struct Node* prev = NULL;
while (cur != NULL && cur->val != x) {
prev = cur;
cur = cur->next;
}
if (cur == NULL) {
prev->next = newNode;
} else {
if (prev == NULL) {
newNode->next = head;
head = newNode;
} else {
prev->next = newNode;
newNode->next = cur;
}
}
}
void delete(int x) {
if (head == NULL) {
return;
}
struct Node* cur = head;
struct Node* prev = NULL;
while (cur != NULL && cur->val != x) {
prev = cur;
cur = cur->next;
}
if (cur == NULL) {
return;
}
if (prev == NULL) {
head = cur->next;
} else {
prev->next = cur->next;
}
free(cur);
}
int main() {
insert(1, 10);
insert(2, 20);
insert(3, 30);
insert(4, 40);
insert(5, 50);
delete(3);
delete(1);
struct Node* cur = head;
while (cur != NULL) {
printf("%d ", cur->val);
cur = cur->next;
}
return 0;
}
```
注意:这个代码只是一个简单的实现,没有考虑一些边界情况,比如链表为空、删除的节点是头节点等。在实际应用中,需要根据具体情况进行修改和完善。
阅读全文