#include "pch.h" #include <iostream> //创建链表 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编译
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。