您好,登錄后才能下訂單哦!
這篇文章主要介紹“C++鏈表類怎么封裝”的相關知識,小編通過實際案例向大家展示操作過程,操作方法簡單快捷,實用性強,希望這篇“C++鏈表類怎么封裝”文章能幫助大家解決問題。
#ifndef CLIST_H #define CLIST_H class CNode //節點類 { public: CNode(); ~CNode(); void *data; //數據域 節點數據的地址 CNode *pnext; //指針域 保存下一個節點的地址 protected: private: }; class CList //鏈表類 { public: CList(); ~CList(); void addList(void *data); //在尾部添加節點 int getListCount(); //獲取節點的個數 int insertListByPos(int pos,void *data); //根據pos插入節點 int deleteListByPos(int pos); //刪除節點 void *getNodeByPos(int pos); //獲取節點數據 void *freeList(); //釋放鏈表 protected: private: CNode *head; //鏈表頭 int count; //節點個數 }; #endif
#include"CList.h" #include<stdio.h> #include<cstring>//memset頭文件 CNode::CNode() { this->data = NULL; this->pnext = NULL; } CNode::~CNode() { } CList::CList() { this->head = new CNode; this->count = 0; } CList::~CList() { } //在尾部添加節點 void CList::addList(void *data) { CNode *tmp = this->head; while(tmp->pnext!=NULL) { tmp = tmp->pnext; } CNode *newNode = new CNode;//創建新節點 tmp->pnext = newNode; newNode->data = data; ++(this->count); } //獲取節點的個數 int CList::getListCount() { return this->count; } //根據pos插入節點 int CList::insertListByPos(int pos,void *data) { int num = 0; CNode* tmp = this->head; while(tmp->pnext!=NULL) { count++; tmp = tmp->pnext; if(pos == count) { CNode* newNode = new CNode; //新節點 memset(newNode,'\0',sizeof(CNode)); newNode->data = data; newNode->pnext = tmp->pnext; tmp->pnext = newNode; return 1; } } return 0; } //刪除節點 int CList::deleteListByPos(int pos) { int count = 0; CNode* tmp = head->pnext,*pre = head; while(tmp!=NULL) { count++; if(count == pos) { pre->pnext = tmp->pnext; //tmp數據域釋放掉 delete tmp->data; delete tmp; return 1; } pre = pre->pnext; tmp = tmp->pnext; } return -1; } //獲取節點數據 void* CList::getNodeByPos(int pos) { int count = 0; CNode* tmp = head; while(tmp->pnext!=NULL) { count++; tmp = tmp->pnext; if(pos == count) { return tmp->data; } } return NULL; } //釋放鏈表 void* CList::freeList() { CNode* tmp = head; while(tmp!=NULL) { head = head->pnext; delete tmp->data; delete tmp; tmp = head; } return this->head; }
計算總節點數:
#include<iostream> using namespace std; #include"CTools.h" #include "CLabel.h" #include"CEdit.h" #include"CButton.h" #include"CtrBase.h" #include"CLogin.h" //顯示登錄窗口 #include"CIndexWin.h" //管理員主界面窗口 #include"CManagerWin.h" //經理主界面窗口 #include"CWaiterWin.h" //服務員主界面窗口 #include<stdlib.h> #include"CList.h" int main() { CLoginWin *login = new CLoginWin(12,5,30,20); CIndexWin *index = new CIndexWin(3,3,25,23); CManagerWin *manager = new CManagerWin(3,3,25,23); CWaiterWin *waiter = new CWaiterWin(3,3,25,30); CList *myList = new CList; myList->addList(login); myList->addList(index); myList->addList(manager); myList->addList(waiter); cout<<myList->getListCount()<<endl;//4 return 0; }
關于“C++鏈表類怎么封裝”的內容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業相關的知識,可以關注億速云行業資訊頻道,小編每天都會為大家更新不同的知識點。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。