C链表操作
链表创建删除插入查找销毁操作
#include<stdio.h> #include<string.h> #include<stdlib.h> typedef struct Node { int data; struct Node *next; }SLIST; SLIST *SList_Create(); int SList_Print(SLIST *pHead); int SList_NodeInsert(SLIST *pHead, int x, int y); int SList_NodeDel(SLIST *pHead, int y); int SList_Destory(SLIST *pHead); int SList_Reverse(SLIST *pHead); int main() { int ret = 0; SLIST *pHead = NULL; pHead = SList_Create(); ret = SList_Print(pHead); ret = SList_NodeInsert(pHead, 20, 19); ret = SList_Print(pHead); ret = SList_NodeDel(pHead, 19); ret = SList_Print(pHead); ret = SList_Reverse(pHead); ret = SList_Print(pHead); SList_Destory(pHead); return 0; } SLIST *SList_Create() { SLIST *pHead, *pM, *pCur; int data; pHead = (SLIST *)malloc(sizeof(SLIST)); if (pHead == NULL) { return NULL; } pHead->data = 0; pHead->next = NULL; printf("please enter yout data : "); scanf("%d", &data); pCur = pHead; while (-1 != data) { pM = (SLIST *)malloc(sizeof(SLIST)); if (NULL == pM) { return NULL; } pM->data = data; pM->next = NULL; pCur->next = pM; pCur = pM; printf("\nplease enter yout data : "); scanf("%d", &data); } return pHead; } int SList_Print(SLIST *pHead) { SLIST *tmp = NULL; if (NULL == pHead) { return -1; } tmp = pHead->next; printf("\nbegin\t"); while(tmp) { printf("%d ", tmp->data); tmp = tmp->next; } printf("\tEnd\n"); return 0; } int SList_NodeInsert(SLIST *pHead, int x, int y) { SLIST *pM, *pCur, *pPre; pM = (SLIST *)malloc(sizeof(SLIST)); if (NULL == pM) { return -1; } pM->data = y; pM->next = NULL; pPre = pHead; pCur = pHead->next; while(pCur) { if (pCur->data == x) { break; } pPre = pCur; pCur = pCur->next; } pM->next = pPre->next; pPre->next = pM; return 0; } int SList_NodeDel(SLIST *pHead, int y) { SLIST *pCur, *pPre; pPre = pHead; pCur = pHead->next; while(pCur != NULL) { if (pCur->data == y) { break; } pPre = pCur; pCur = pCur->next; } if (pCur == NULL) { printf("Can't find the node that value is %d\n", y); return -1; } pPre->next = pCur->next ; if (pCur != NULL) { free(pCur); } return 0; } int SList_Destory(SLIST *pHead) { SLIST *tmp = NULL; if(NULL == pHead) { return -1; } while(pHead != NULL) { tmp = pHead->next; free(pHead); pHead = tmp; } return 0; } int SList_Reverse(SLIST *pHead) { SLIST *p = NULL; //previous node SLIST *q = NULL; //current node SLIST *t = NULL; //buffer node p = pHead->next; q = pHead->next->next; while(q) { t = q->next; q->next = p; p = q; q = t; } pHead->next->next = NULL; pHead->next = p; return 0; }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)