带头节点单链表的实现c++
时间: 2024-05-07 14:15:31 浏览: 100
基于C++实现的基础数据结构、泛型数据结构及高阶数据结构,含链式栈、顺序栈、单链表、带头双向循环链表、顺序表、泛型数据结构
以下是带头节点单链表的实现 c 代码:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node *next;
} Node;
typedef struct List {
Node *head;
} List;
// 初始化带头节点的单链表
void initList(List *list) {
list->head = (Node *)malloc(sizeof(Node));
list->head->next = NULL;
}
// 在链表尾部插入元素
void insert(List *list, int data) {
Node *p = list->head;
while (p->next != NULL) {
p = p->next;
}
Node *newNode = (Node *)malloc(sizeof(Node));
newNode->data = data;
newNode->next = NULL;
p->next = newNode;
}
// 删除链表中指定元素
void delete(List *list, int data) {
Node *p = list->head;
while (p->next != NULL) {
if (p->next->data == data) {
Node *temp = p->next;
p->next = temp->next;
free(temp);
return;
}
p = p->next;
}
}
// 查找链表中指定元素的位置
int find(List *list, int data) {
Node *p = list->head->next;
int index = 0;
while (p != NULL) {
if (p->data == data) {
return index;
}
index++;
p = p->next;
}
return -1;
}
// 输出链表元素
void printList(List *list) {
Node *p = list->head->next;
while (p != NULL) {
printf("%d ", p->data);
p = p->next;
}
printf("\n");
}
int main() {
List list;
initList(&list);
insert(&list, 1);
insert(&list, 2);
insert(&list, 3);
insert(&list, 4);
insert(&list, 5);
printf("原始链表:");
printList(&list);
delete(&list, 3);
printf("删除元素 3 后的链表:");
printList(&list);
printf("元素 4 在链表中的位置是:%d\n", find(&list, 4));
return 0;
}
```
阅读全文