c语言实现无头结点的单链表
时间: 2023-05-19 15:03:23 浏览: 107
无头结点的单链表的c算法的实现
4星 · 用户满意度95%
可以参考以下代码实现:
```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 = *head;
*head = new_node;
}
void delete(Node **head, int data) {
Node *current = *head;
Node *previous = NULL;
while (current != NULL && current->data != data) {
previous = current;
current = current->next;
}
if (current == NULL) {
printf("Element not found.\n");
return;
}
if (previous == NULL) {
*head = current->next;
} else {
previous->next = current->next;
}
free(current);
}
void display(Node *head) {
Node *current = head;
while (current != NULL) {
printf("%d ", current->data);
current = current->next;
}
printf("\n");
}
int main() {
Node *head = NULL;
insert(&head, 1);
insert(&head, 2);
insert(&head, 3);
insert(&head, 4);
insert(&head, 5);
display(head);
delete(&head, 3);
display(head);
return 0;
}
```
这是一个简单的无头结点的单链表实现,包括插入、删除和显示操作。
阅读全文