C++简单单向链表实现
#include "pch.h" #include//创建链表 typedef struct ListTable { int nElement; //链表元素 int nSequence; //节点序号 ListTable *pNext;//下一个节点 }ListTable; //初始化链表 //参数:元素的值 ListTable* initListTable(int nNum) { //头结点 ListTable *head; //申请内存 head = (ListTable*)malloc(sizeof(ListTable)); //初始化成员变量 head->nElement = nNum; head->nSequence =1; head->pNext = NULL; //返回头结点指针 return head; } //插入元素 //参数:链表指针 元素的值 void insertElement(ListTable *list, int nNum) { //创建局部变量 ListTable *pList = list; int nCount = list->nSequence; //申请新的节点空间 ListTable *pNode = (ListTable*)malloc(sizeof(ListTable)); //遍历链表 while (pList != NULL) { //如果下一个节点为空,则插入元素 if (pList->pNext ==NULL) { pList->pNext = pNode; pNode->nSequence = nCount + 1; pNode->nElement = nNum; pNode->pNext = NULL; return; } nCount += 1; pList = pList->pNext; } } //删除指定序号元素 //参数:链表指针 元素序号 void deleteElement(ListTable *list,int nSequence) { //如果是第一个节点,直接free if (list->nSequence == nSequence) { free(list); return; } //创建局部变量 ListTable *pList = list; ListTable *pTmp=NULL; //遍历链表 while (pList!=NULL) { //如果序号相等,删除指定序号元素 if (pList->pNext->nSequence == nSequence) { pTmp = pList->pNext->pNext; free(pList->pNext); pList->pNext = pTmp; //之后的序号依次减一 while (pTmp != NULL) { pTmp->nSequence -= 1; pTmp = pTmp->pNext; } return; } pList = pList->pNext; } printf("节点不存在!\n"); } //修改元素 //参数:链表指针 元素序号 元素的值 void changeElement(ListTable *list, int nSequence,int nNum) { ListTable *pList = list; while (pList != NULL) { if (pList->nSequence == nSequence) { pList->nElement = nNum; return; } pList = pList->pNext; } printf("节点不存在!\n"); } //释放链表 //参数:链表指针 void deleteListTable(ListTable *list) { ListTable *pList = list; ListTable *pTmp=NULL; while (pList != NULL) { pTmp= pList->pNext; free(pList); pList = pTmp; } printf("释放完成!\n"); } //遍历链表元素 //参数:链表指针 void showElement(ListTable *list) { ListTable *pList = list; if (pList == NULL) { printf("链表为空!\n"); return; } while (pList != NULL) { printf("链表元素:%d 元素序号:%d\n", pList->nElement, pList->nSequence); pList = pList->pNext; } } int main() { //初始化链表 第一个元素为1 ListTable *list= initListTable(1); //插入2,3,4,5四个元素 insertElement(list, 2); insertElement(list, 3); insertElement(list, 4); insertElement(list, 5); //修改序号5的元素为6 changeElement(list, 5, 6); //删除序号为3的元素 deleteElement(list, 3); //遍历 showElement(list); //释放 deleteListTable(list); }
vs2017编译
创新互联是专业的当阳网站建设公司,当阳接单;提供成都网站制作、网站建设、外贸网站建设,网页设计,网站设计,建网站,PHP网站建设等专业做网站服务;采用PHP框架,可快速的进行当阳网站开发网页制作和功能扩展;专业做搜索引擎喜爱的网站,专业的做网站团队,希望更多企业前来合作!
网页标题:C++简单单向链表实现
文章分享:http://azwzsj.com/article/jjgedd.html