编写主函数,在主函数中调,用建立单链表的算法创建一个单链表,然后调用查找,插入,删除算法,运行调试,输入数据,并根据结果进行分析,C语言编写
时间: 2024-11-06 20:18:03 浏览: 22
在C语言中,你可以按照以下步骤编写一个主函数来操作单链表:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义单链表节点结构体
typedef struct Node {
int data;
struct Node* next;
} Node;
// 创建链表节点的函数
Node* createNode(int value) {
Node* newNode = (Node*)malloc(sizeof(Node));
if (newNode != NULL) {
newNode->data = value;
newNode->next = NULL;
}
return newNode;
}
// 插入节点到链表的函数
void insertNode(Node** head, int value) {
Node* newNode = createNode(value);
if (*head == NULL) {
*head = newNode;
} else {
Node* temp = *head;
while (temp->next != NULL) {
temp = temp->next;
}
temp->next = newNode;
}
}
// 查找节点的函数
Node* searchNode(Node* head, int value) {
Node* current = head;
while (current != NULL) {
if (current->data == value)
return current;
current = current->next;
}
return NULL;
}
// 删除节点的函数
void deleteNode(Node** head, int value) {
Node* temp = *head, *prev = NULL;
if (temp != NULL && temp->data == value) {
*head = temp->next; // 如果头节点就是目标节点,直接移除头节点
free(temp);
return;
}
while (temp != NULL && temp->data != value) {
prev = temp;
temp = temp->next;
}
if (temp == NULL) // 节点未找到
return;
prev->next = temp->next;
free(temp); // 释放已找到的节点内存
}
int main() {
// 初始化链表为空
Node* head = NULL;
// 调用创建链表函数并插入示例数据
int values[] = {1, 2, 3, 4, 5};
for (int i = 0; i < sizeof(values) / sizeof(values[0]); i++) {
insertNode(&head, values[i]);
}
// 打印链表内容进行初步检查
printf("Original List: ");
printList(head);
// 示例操作:查找、插入、删除节点
int searchValue = 3;
Node* found = searchNode(head, searchValue);
if (found != NULL) {
printf("Found %d at position %p\n", searchValue, &found);
} else {
printf("Element not found.\n");
}
int insertValue = 6;
insertNode(&head, insertValue);
printf("\nAfter inserting %d: ", insertValue);
printList(head);
int deleteValue = 2;
deleteNode(&head, deleteValue);
printf("\nAfter deleting %d: ", deleteValue);
printList(head);
return 0;
}
// 辅助函数:打印链表
void printList(Node* head) {
while (head != NULL) {
printf("%d -> ", head->data);
head = head->next;
}
printf("NULL\n");
}
阅读全文