c语言链表的增删查找
时间: 2023-12-05 21:05:16 浏览: 29
以下是C语言链表的增删查找的示例代码:
1.链表的定义
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
int data;
struct node *next;
} Node, *LinkedList;
```
2.链表的初始化
```c
LinkedList initLinkedList() {
LinkedList L = (LinkedList) malloc(sizeof(Node));
if (L == NULL) {
printf("申请内存失败!\n");
exit(0);
}
L->next = NULL;
return L;
}
```
3.链表的插入
```c
void insertLinkedList(LinkedList L, int data, int position) {
Node *p = L;
int j = 0;
while (p != NULL && j < position - 1) {
p = p->next;
j++;
}
if (p == NULL || j > position - 1) {
printf("插入位置错误!\n");
exit(0);
}
Node *newNode = (Node *) malloc(sizeof(Node));
newNode->data = data;
newNode->next = p->next;
p->next = newNode;
}
```
4.链表的删除
```c
void deleteLinkedList(LinkedList L, int position) {
Node *p = L;
int j = 0;
while (p->next != NULL && j < position - 1) {
p = p->next;
j++;
}
if (p->next == NULL || j > position - 1) {
printf("删除位置错误!\n");
exit(0);
}
Node *q = p->next;
p->next = q->next;
free(q);
}
```
5.链表的查找
```c
int findLinkedList(LinkedList L, int data) {
Node *p = L->next;
int i = 1;
while (p != NULL && p->data != data) {
p = p->next;
i++;
}
if (p == NULL) {
return -1;
} else {
return i;
}
}
```