链表的加入删除C语言代码
时间: 2024-05-14 18:14:54 浏览: 57
以下是链表的加入删除C语言代码:
1. 声明链表结构体
```
struct Node {
int data;
struct Node* next;
};
```
2. 创建新节点并加入链表
```
struct Node* createNode(int data) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = data;
newNode->next = NULL;
return newNode;
}
void insertNode(struct Node** head, int data) {
struct Node* newNode = createNode(data);
if (*head == NULL) {
*head = newNode;
} else {
struct Node* temp = *head;
while (temp->next != NULL) {
temp = temp->next;
}
temp->next = newNode;
}
}
```
3. 删除指定节点
```
void deleteNode(struct Node** head, int data) {
struct Node* temp = *head;
struct Node* prev = NULL;
if (temp != NULL && temp->data == data) {
*head = temp->next;
free(temp);
return;
}
while (temp != NULL && temp->data != data) {
prev = temp;
temp = temp->next;
}
if (temp == NULL) {
return;
}
prev->next = temp->next;
free(temp);
}
```
阅读全文