给我一个C语言写的链表代码
时间: 2024-05-01 11:21:53 浏览: 95
下面是一个简单的 C 语言链表代码示例:
```c
#include <stdio.h>
#include <stdlib.h>
// 链表节点
struct Node {
int data;
struct Node* next;
};
// 在链表头部插入节点
struct Node* insert(struct Node* head, int val) {
struct Node* node = (struct Node*)malloc(sizeof(struct Node));
node->data = val;
node->next = head;
return node;
}
// 删除链表中的节点
struct Node* delete(struct Node* head, int val) {
struct Node* prev = NULL;
struct Node* curr = head;
while (curr != NULL) {
if (curr->data == val) {
if (prev == NULL) {
head = curr->next;
} else {
prev->next = curr->next;
}
free(curr);
break;
}
prev = curr;
curr = curr->next;
}
return head;
}
// 打印链表
void printList(struct Node* head) {
while (head != NULL) {
printf("%d ", head->data);
head = head->next;
}
}
int main() {
struct Node* head = NULL;
head = insert(head, 3);
head = insert(head, 5);
head = insert(head, 6);
head = insert(head, 9);
printList(head);
head = delete(head, 5);
printf("\n");
printList(head);
return 0;
}
```
这是一个简单的链表实现,包含插入和删除节点操作,并且可以打印链表。你可以根据需要进行修改和扩展。
阅读全文