用c语言写单链表的创建、插入、删除、查找、显示
时间: 2023-05-28 15:08:12 浏览: 60
单链表的基本操作包括:创建、插入、删除、查找、显示。下面是使用C语言实现单链表基本操作的代码:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义单链表结构体
typedef struct Node {
int data; // 数据域
struct Node *next; // 指针域
} Node, *List;
// 创建单链表
List createList() {
List head = (List)malloc(sizeof(Node)); // 创建头结点
head->next = NULL; // 头结点的指针域置为NULL
return head;
}
// 插入节点
List insertNode(List head, int data, int index) {
Node *newNode = (Node *)malloc(sizeof(Node)); // 创建新节点
newNode->data = data;
newNode->next = NULL;
if (index == 0) { // 插入到头结点后面
newNode->next = head->next;
head->next = newNode;
} else { // 插入到链表中间或末尾
Node *p = head->next;
int i = 1;
while (p && i < index) { // 找到待插入位置的前一个节点
p = p->next;
i++;
}
if (!p || i > index) { // 如果index值不合法,则返回原链表
printf("插入位置不合法!\n");
return head;
}
newNode->next = p->next;
p->next = newNode;
}
return head;
}
// 删除节点
List deleteNode(List head, int index) {
if (index < 0) { // 如果index值不合法,则返回原链表
printf("删除位置不合法!\n");
return head;
}
Node *p = head->next;
Node *q = head;
int i = 0;
while (p && i < index) { // 找到待删除节点
q = p;
p = p->next;
i++;
}
if (!p) { // 如果index超出链表长度,则返回原链表
printf("删除位置不合法!\n");
return head;
}
q->next = p->next;
free(p); // 释放节点空间
return head;
}
// 查找节点
int findNode(List head, int data) {
Node *p = head->next;
int index = 0;
while (p) {
if (p->data == data) {
return index;
}
p = p->next;
index++;
}
return -1; // 如果找不到,则返回-1
}
// 显示链表
void displayList(List head) {
Node *p = head->next;
while (p) {
printf("%d ", p->data);
p = p->next;
}
printf("\n");
}
int main() {
List head = createList();
head = insertNode(head, 1, 0);
head = insertNode(head, 2, 0);
head = insertNode(head, 3, 1);
head = insertNode(head, 4, 2);
displayList(head); // 输出:2 1 3 4
head = deleteNode(head, 3);
displayList(head); // 输出:2 1 3
int index = findNode(head, 1);
printf("1的位置是:%d\n", index); // 输出:1的位置是:1
return 0;
}
```