增删改查有序链表
#include <stdio.h> #include <stdlib.h> // 定义链表节点结构体 typedef struct Node { int data; struct Node* next; } Node; // 头指针(全局变量) Node* head = NULL;
插入
void insertSorted(int value) { Node* newNode = (Node*)malloc(sizeof(Node)); if (!newNode) { printf("内存分配失败!\n"); exit(1); } newNode->data = value; newNode->next = NULL; // 情况1:链表为空或新值小于等于头节点 if (head == NULL || value <= head->data) { newNode->next = head; head = newNode; return; } // 情况2:寻找插入位置 Node* current = head; while (current->next != NULL && current->next->data < value) { current = current->next; } newNode->next = current->next; current->next = newNode; }
删
void deleteNode(int value) { if (head == NULL) { printf("链表为空!\n"); return; } // 处理头节点是要删除的节点的情况 if (head->data == value) { Node* temp = head; head = head->next; free(temp); return; } Node* current = head; while (current->next != NULL && current->next->data != value) { current = current->next; } if (current->next == NULL) { printf("未找到值为 %d 的节点!\n", value); return; } // 找到目标节点并删除 Node* temp = current->next; current->next = temp->next; free(temp); }
改
void updateNode(int oldValue, int newValue) { Node* target = searchNode(oldValue); if (target == NULL) { printf("未找到值为 %d 的节点!\n", oldValue); return; } target->data = newValue; printf("已将 %d 修改为 %d\n", oldValue, newValue); }
查
Node* searchNode(int value) { Node* current = head; while (current != NULL) { if (current->data == value) { return current; // 返回找到的节点指针 } current = current->next; } return NULL; // 未找到 }
打印链表
void printList() { Node* current = head; printf("链表内容:"); while (current != NULL) { printf("%d -> ", current->data); current = current->next; } printf("NULL\n"); }
完整测试代码
int main() { // 初始化链表 head = NULL; // 插入测试 insertSorted(5); insertSorted(3); insertSorted(7); insertSorted(1); insertSorted(9); printList(); // 输出: 1 -> 3 -> 5 -> 7 -> 9 -> NULL // 查找测试 Node* found = searchNode(5); if (found) { printf("找到值为 5 的节点。\n"); } else { printf("未找到值为 5 的节点。\n"); } // 修改测试 updateNode(5, 6); printList(); // 输出: 1 -> 3 -> 6 -> 7 -> 9 -> NULL // 删除测试 deleteNode(3); printList(); // 输出: 1 -> 6 -> 7 -> 9 -> NULL // 删除不存在的节点 deleteNode(10); // 输出: 未找到值为 10 的节点! // 清空链表 while (head != NULL) { deleteNode(head->data); } printList(); // 输出: 链表内容:NULL return 0; }