酷代码 AI
菜单
服务商

C语言实现链表创建、输出、删除与插入操作的完整代码及注意要点

以下是用 C 语言实现上述链表功能的代码: ```c #include <stdio.h> #include <stdlib.h> // 定义链表节点结构体 typedef struct Node { int data; struct Node *next; // 构造函数,初始化节点 Node(int x) : data(x), next(NULL) {} } Node; // 定义操作状态枚举类型 typedef enum OprStatus { OK, ERROR } OprStatus; // 创建链表函数 Node* create() { Node* head = NULL; return head; } // 输出链表函数 OprStatus show(Node* head) { if (head == NULL) { return ERROR; } Node* curr = head; while (curr!= NULL) { printf("%d ", curr->data); curr = curr->next; } printf("\n"); return OK; } // 删除链表数据函数 OprStatus delete(Node* head, int i) { if (head == NULL) { return ERROR; } if (i == 1) { Node* temp = head; head = head->next; free(temp); return OK; } Node* curr = head; int count = 1; while (curr!= NULL && count < i - 1) { curr = curr->next; count++; } if (curr == NULL || curr->next == NULL) { return ERROR; } Node* temp = curr->next; curr->next = curr->next->next; free(temp); return OK; } // 插入数据函数 OprStatus insert(Node* head, int data) { Node* newNode = (Node*)malloc(sizeof(Node)); newNode->data = data; newNode->next = head; head = newNode; return OK; } int main() { Node* head = create(); insert(head, 10); insert(head, 20); insert(head, 30); show(head); delete(head, 2); show(head); return 0; } ``` 额外需要注意的逻辑点: 1. 在删除节点时,要处理好删除头节点和中间节点的不同情况。 2. 插入节点时,要确保内存分配成功,否则可能导致程序崩溃。 3. 在操作链表的过程中,注意边界情况,如空链表、只有一个节点的链表等。 ######[AI写代码神器 | 609点数解答 | 2024-12-18 12:18:21]

相关提问
本站限时免费提问中
实用工具查看更多
Linux在线手册 [开发类]
Jquery在线手册 [开发类]
今日油价 [生活类]
图片互转base64 [开发类]
时间转换器 [开发类]