请写出一个C语言的基本链表操作
时间: 2024-05-02 16:19:40 浏览: 10
Sure, here is an example of basic linked list operations in C:
```
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
int data;
struct node* next;
} Node;
void insert(Node** head, int data) {
Node* new_node = (Node*)malloc(sizeof(Node));
new_node->data = data;
new_node->next = NULL;
if (*head == NULL) {
*head = new_node;
return;
}
Node* cur = *head;
while (cur->next != NULL) {
cur = cur->next;
}
cur->next = new_node;
}
void print_list(Node* head) {
Node* cur = head;
while (cur != NULL) {
printf("%d ", cur->data);
cur = cur->next;
}
printf("\n");
}
void delete(Node** head, int data) {
if (*head == NULL) {
return;
}
if ((*head)->data == data) {
Node* temp = *head;
*head = (*head)->next;
free(temp);
return;
}
Node* cur = *head;
while (cur->next != NULL) {
if (cur->next->data == data) {
Node* temp = cur->next;
cur->next = cur->next->next;
free(temp);
return;
}
cur = cur->next;
}
}
int main() {
Node* head = NULL;
insert(&head, 1);
insert(&head, 2);
insert(&head, 3);
print_list(head);
delete(&head, 2);
print_list(head);
return 0;
}
```
This program demonstrates basic linked list operations, including insertion and deletion of nodes, and printing the linked list. The `insert()` function adds a new node to the end of the linked list, and the `delete()` function removes the node with the given `data` value from the linked list. The `print_list()` function simply prints the contents of the linked list.