要求编写一个C语言代码。要求完成线性表的链式存储结构的C语言描述,和单链表的建立、插入、删除、查找等基本操作的实现。
时间: 2024-06-13 07:05:13 浏览: 204
以下是基于单链表的C语言代码实现,包括链表的建立、插入、删除和查找等基本操作:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义链表结点
typedef struct Node {
int data; // 数据域
struct Node *next; // 指针域
} Node;
// 初始化链表
void initList(Node **head) {
*head = NULL;
}
// 在链表头部插入结点
void insertAtHead(Node **head, int data) {
Node *newNode = (Node*)malloc(sizeof(Node));
newNode->data = data;
newNode->next = *head;
*head = newNode;
}
// 在链表尾部插入结点
void insertAtTail(Node **head, int data) {
Node *newNode = (Node*)malloc(sizeof(Node));
newNode->data = data;
newNode->next = NULL;
if (*head == NULL) {
*head = newNode;
} else {
Node *temp = *head;
while (temp->next != NULL) {
temp = temp->next;
}
temp->next = newNode;
}
}
// 在链表中查找指定值的结点
Node* search(Node *head, int data) {
Node *temp = head;
while (temp != NULL) {
if (temp->data == data) {
return temp;
}
temp = temp->next;
}
return NULL;
}
// 删除链表中指定值的结点
void delete(Node **head, int data) {
Node *temp = *head;
Node *prev = NULL;
while (temp != NULL) {
if (temp->data == data) {
if (prev == NULL) {
*head = temp->next;
} else {
prev->next = temp->next;
}
free(temp);
return;
}
prev = temp;
temp = temp->next;
}
}
// 打印链表
void printList(Node *head) {
Node *temp = head;
while (temp != NULL) {
printf("%d ", temp->data);
temp = temp->next;
}
printf("\n");
}
int main() {
Node *head;
initList(&head);
insertAtHead(&head, 1);
insertAtHead(&head, 2);
insertAtTail(&head, 3);
insertAtTail(&head, 4);
printList(head);
Node *node = search(head, 3);
if (node != NULL) {
printf("Found: %d\n", node->data);
} else {
printf("Not found\n");
}
delete(&head, 2);
printList(head);
return 0;
}
```
阅读全文
相关推荐


















