您好,登錄后才能下訂單哦!
這篇文章給大家分享的是有關(guān)C++中數(shù)據(jù)結(jié)構(gòu)線性表之?dāng)?shù)組實(shí)現(xiàn)的示例分析的內(nèi)容。小編覺得挺實(shí)用的,因此分享給大家做個參考,一起跟隨小編過來看看吧。
C++ 數(shù)據(jù)結(jié)構(gòu)線性表-數(shù)組實(shí)現(xiàn)
/* Author : Moyiii * 線性表的數(shù)組實(shí)現(xiàn),僅作學(xué)習(xí)之用,當(dāng)然如果 * 你想拿去用,隨你好啦。 */ #include<iostream> using namespace std; //順序表 class SeqList { public: //構(gòu)造函數(shù),接受一個默認(rèn)的列表大小 SeqList(int size = MAX_LIST_SIZE); //析構(gòu)函數(shù),釋放elems占用的內(nèi)存空間 ~SeqList(); //清空表 void clear(); //判斷表是否為空 bool isEmpty(); //獲得表的當(dāng)前元素個數(shù) int getLength(); //在第pos個元素位置之前插入一個新元素 bool insertElem(int pos, int elem); //刪除第pos個元素 bool deleteElem(int pos); //打印表中元素 void print(); int *elems;//表元素, private: static const int MAX_LIST_SIZE; int m_length;//表的元素個數(shù) int m_size;//表的當(dāng)前最大長度 }; SeqList :: SeqList(int size) { //size不可以小于零,也不可以超過系統(tǒng)規(guī)定最大長度 //否則做截斷處理 if(size > MAX_LIST_SIZE) { m_size = MAX_LIST_SIZE; } else if(size < 0) { m_size = 0; } else { m_size = size; } elems = new int[m_size]; m_length = 0; if(!elems) { cout << "Space allocate failed!" << endl; } } SeqList :: ~SeqList() { delete []elems; } void SeqList :: clear() { m_length = 0; } bool SeqList :: isEmpty() { if(m_length == 0) { return true; } else { return false; } } int SeqList :: getLength() { return m_length; } bool SeqList :: insertElem(int pos, int elem) { if(m_length == m_size) { cout << "List is Full" << endl; return false; } if(pos < 1 || pos > m_length + 1) { cout << "Over Bound!" << endl; return false; } //插入位置之后元素后移 for(int i = m_length; i >= pos - 1; --i) { elems[i+1] = elems[i]; } elems[pos-1] = elem; m_length++; return true; } bool SeqList :: deleteElem(int pos) { if(pos < 1 || pos > m_length) { return false; } for(int i = pos - 1; i <= m_length - 1; ++i) { elems[i] = elems[i+1]; } m_length--; return false; } void SeqList :: print() { for(int i = 0; i < m_length; ++i) { cout << elems[i] << " "; } cout << endl; } //初始化 const int SeqList :: MAX_LIST_SIZE = 100; int main() { SeqList myList; for(int i = 1; i <= 10; ++i) { myList.insertElem(1,i); } myList.print(); cout << "Length= " << myList.getLength() <<endl; myList.deleteElem(5); myList.print(); cout << "Length= " << myList.getLength() <<endl; myList.clear(); cout << myList.isEmpty() << endl; return 0; }
感謝各位的閱讀!關(guān)于“C++中數(shù)據(jù)結(jié)構(gòu)線性表之?dāng)?shù)組實(shí)現(xiàn)的示例分析”這篇文章就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,讓大家可以學(xué)到更多知識,如果覺得文章不錯,可以把它分享出去讓更多的人看到吧!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。