头文件:
#ifndef LIST_H
#define LIST_H
class List
{
public:
List(int size);//线性表的长度
~List();
void ClearList();
bool ListEmpty();
int ListLength();
bool GetElem(int i,int *e);
int LocateElem(int *e);
bool PriorElem(int*currentElem,int*preElem);
bool NextElem(int *currentElem,int*nextElem);
void ListTraverse();
bool ListInsert(int i,int*e);//
bool ListDelete(int i,int*e);
private://需要数据成员来指向一段内存,也就是一段数组
int *m_pList;//用这个指针来指向一个内存,指针数组
int m_iSize;//来存储大小(数组)
int m_iLength;//元素的个数
};
#endif
#include "List.H"
#include <iostream>
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;//这个指针指向null
}
//清列表
void List::ClearList()
{
m_iLength=0;
}
//判表空
bool List::ListEmpty()
{
if(m_iLength==0)
{
return true;
}
else
{ return false;}
}
//求表长
int List::ListLength()
{
return m_iLength;
}
//获取存在
bool List::GetElem(int i,int *e)
{
if(i<0 || i>=m_iSize)
{return false;}
*e=m_pList[i];
return true;
}
//获取数组位置
int List:: LocateElem(int *e)
{
for(int i=0;i<m_iLength;i++)
{
if(m_pList[i]==*e)
{
return i;
}
}
return -1;
}
//获取指定元素的前驱
bool List::PriorElem(int*currentElem,int*preElem)
{
int temp=LocateElem(currentElem);//寻找当前元素的位置
if(temp==-1)
{
return false;
}
else
{
*preElem=m_pList[temp-1];//获取当前序号的前一个元素
return true;
}
}
//获取指定元素的后继
bool List::NextElem(int *currentElem,int *nextElem)
{
int temp=LocateElem(currentElem);
if(temp==-1)
{return false;}
else
{*nextElem=m_pList[temp+1];//后面的指付给它
return true;}
}
//遍历
void List::ListTraverse()
{
for(int i=0;i<m_iLength;i++)
{
cout<<m_pList[i]<<endl;
}
}
bool List::ListInsert(int i,int*e)
{
if(i<0||i>m_iLength)
{return false;
}
for(int k=m_iLength-1;k>=i;k--)
{m_pList[k+1]=m_pList[k];}
m_pList[i]=*e;
m_iLength++;
return true;
}
bool List::ListDelete(int i,int *e)
{
if(i<0||i>=m_iLength)
{return false;
}
*e=m_pList[i];
for(int k=i+1;k>m_iLength-1;k++)
{m_pList[k-1]=m_pList[k];}
m_iLength--;
return true;
}
int main()
{
//3 5 7 2 9 1 8
int e1=1;
int e2=2;
int e3=3;
int e4=4;
int e5=5;
int e6=6;
int e7=7;
List*list1=new List(10);
list1->ListInsert(0,&e1);
list1->ListInsert(1,&e2);
list1->ListInsert(2,&e3);
list1->ListInsert(3,&e4);
list1->ListInsert(4,&e5);
list1->ListInsert(5,&e6);
list1->ListInsert(6,&e7);
list1->ListTraverse();
int temp;//3
list1->GetElem(2,&temp);//int *e=&temp; int*e,e=&temp
cout<<temp<<endl;
int temp1;//4
temp1=list1->LocateElem(&e5);//int *e=&temp; int*e,e=&temp
cout<<temp1<<endl;
int temp2;//1
list1->PriorElem(&e2,&temp2);//int *e=&temp; int*e,e=&temp
cout<<temp2<<endl;
int temp3;//3
list1->NextElem(&e2,&temp3);//int *e=&temp; int*e,e=&temp
cout<<temp3<<endl;
delete list1;
system("pause");
return 0;
};