file:List.hpp
#ifndef List_hpp
#define List_hpp
#include
class List{
public:
List(int size);
~List();
void clearList();
bool ListEmpty();
int ListLength();
bool getElem(int i,int &elem);
int locateElem(int elem);
bool priorElem(int *currentElem,int *preElem);
bool nextElem(int *currentElem,int *nextElem);
void ListTraverse();
bool ListInsert(int i,int *Elem);
bool ListDelete(int i,int *Elem);
private:
int *m_pList;
int m_iSize;
int m_iLength;
};
#endif /* List_hpp */ file:List.cpp
#include "List.hpp"
#include
using namespace std;
List::List(int size){
m_iSize = size;
m_pList = new int[m_iSize];
m_iLength = 0;
}
List::~List(){
delete []m_pList;
m_pList = NULL;
}
void List::clearList(){
m_iLength = 0;
}
bool List::ListEmpty(){
return m_iLength==0?true:false;
}
int List::ListLength(){
return m_iLength;
}
bool List::getElem(int i , int &elem){
if(i m_iLength){
return false;
}
else{
elem = m_pList[i];
return true;
}
}
int List::locateElem(int elem){
for(int i = 0;i m_iLength){
return false;
}
for(int j = m_iLength;j >= i;j--){
m_pList[j+1] = m_pList[j];
}
m_pList[i] = *Elem;
m_iLength++;
return true;
}
bool List::ListDelete(int i,int *Elem){
if(i m_iLength){
return false;
}
*Elem = m_pList[i];
for(int j = i + 1;j file:demo.cpp
#include
#include
#include "List.hpp"
using namespace std;
int main(void){
List *p = new List(30);
int e1 = 1;
int e2 = 2;
int e3 = 3;
int e4 = 4;
int e5 = 5;
int e6 = 6;
int e7 = 7;
int e8 = 8;
int e9 = 9;
p->ListInsert(0,&e1);
p->ListTraverse();
p->ListInsert(1,&e2);
p->ListTraverse();
p->ListInsert(2,&e3);
p->ListTraverse();
p->ListInsert(2,&e4);
p->ListTraverse();
p->ListInsert(2,&e5);
p->ListTraverse();
p->ListInsert(2,&e6);
p->ListTraverse();
p->ListInsert(2,&e7);
p->ListTraverse();
p->ListInsert(2,&e8);
p->ListTraverse();
p->ListInsert(2,&e9);
p->ListTraverse();
int Elem = 0;
p->ListDelete(3,&Elem);
cout ListTraverse();
cout ListLength() nextElem(&e1, &Elem);
cout priorElem(&e2, &Elem);
cout locateElem(e5) getElem(3,Elem);
cout clearList();
if(p->ListEmpty()){
cout ListTraverse();
delete p;
p = NULL;
} 结果如下: