<span style="font-size:18px;">// LinkList.cpp : Defines the entry point for the console application.
//
//#include "stdafx.h"
#include <malloc.h>
#include <iostream>
using namespace std;
#define LIST_INIT_SIZE 10 /* 线性表存储空间的初始分配量 */
#define LIST_INCREMENT 2 /* 线性表存储空间的分配增量 */
typedef int ElemType ;
class ArrayList
{
private :
ElemType *elem; /* 存储空间基址 */
int length; /* 当前长度 */
int listsize; /* 当前分配的存储容量(以sizeof(ElemType)为单位) */
public:
ArrayList()
{//不指定长度,则默认为LIST_INIT_SIZE
ArrayList(LIST_INIT_SIZE);
}
ArrayList(int size)
{//构造函数,可以指定长度size
elem=(ElemType*)malloc(size*sizeof(ElemType));
if(!elem)
{
cout << "分配内存失败!\n";
exit(-1); /* 存储分配失败 */
}
length=0;
listsize=size;
//调试初始化信息
//cout << "elem=" << elem << " length=" << length << " listsize=" << listsize << endl;
}
void Init(int len)
{
if(len>listsize)
cout << "初始化失败!" << endl;
for(int i=0;i<len;i++)
{
*(elem+i)=i;
//cout << *(elem+i) << ' ';
length=len;
}
}
void Show()
{//显示LinkList中的所有元素
//cerr << "length=" << length << endl;
for(int i=0;i<length;i++)
{
cout << *(elem+i) << ' ';
}
cout << endl;
}
void Destroy()
{//释放申请的内存空间
if(NULL==elem)
cout << "没有需要释放的!\n";
else
{
free(elem);
elem=NULL;
length=0;
listsize=0;
cout << "elem=NULL length=0 listsize=0 释放完毕!\n";
}
}
void Clear()
{ /* 初始条件:顺序线性表L已存在。操作结果:将L重置为空表 */
length=0;
}
bool IsEmpty()
{ /* 初始条件:顺序线性表L已存在。操作结果:若L为空表,则返回TRUE,否则返回FALSE */
if(length==0)
return true;
else
return false;
}
int ListLength()
{ /* 初始条件:顺序线性表L已存在。操作结果:返回L中数据元素个数 */
return length;
}
bool GetElem(int i,ElemType *e)
{ /* 初始条件:顺序线性表L已存在,1≤i≤ListLength(L)。操作结果:用e返回L中第i个数据元素的值 */
if(i<1||i>length)
return false;
*e=*(elem+i-1);
return true;
}
bool Insert(int i,ElemType e)
{
/* 初始条件:顺序线性表L已存在,1≤i≤ListLength(L)+1 */
/* 操作结果:在L中第i个位置之前插入新的数据元素e,L的长度加1 */
if(i<1 || i>length+1)
{
cout << "插入的位置不对!" << endl;/* i值不合法 */
return false;
}
//cout << "length=" << length << endl;
ElemType *newbase;
if(length>=listsize)
{
newbase=(ElemType*)realloc(elem,(listsize+LIST_INCREMENT) * sizeof(ElemType));
if(!newbase)/* 存储分配失败 */
return false;
elem=newbase;/* 新基址 */
listsize+=LIST_INCREMENT;/* 增加存储容量 */
}
//cout << "length=" << length << endl;
ElemType *p,*q;
/*q=elem+length-1;
for(p=q;p>=elem+i-1;p--)
*(p+1)=*p;
*p=e;*/
q=elem+i-1; // q为插入位置 //
for(p=elem+length-1;p>=q;--p) // 插入位置及之后的元素右移 //
*(p+1)=*p;
*q=e;
length+=1;
cout << "length=" << length << endl;
return true;
}
bool Delete(int i,ElemType* e)
{
ElemType *p,*q;
if(i<1||i>length) /* i值不合法 */
{
cout << "删除的位置不对!\n";
return false;
}
p=elem+i-1; /* p为被删除元素的位置 */
*e=*p; /* 被删除元素的值赋给e */
q=elem+length-1; /* 表尾元素的位置 */
for(++p;p<=q;++p) /* 被删除元素之后的元素左移 */
*(p-1)=*p;
length--; /* 表长减1 */
cout << "您删除的元素是:" << *e << endl;
return true;
}
};
int main()
{
ArrayList* _ll=new ArrayList(5);
_ll->Init(5);
_ll->Show();
_ll->Insert(3,155);
_ll->Show();
_ll->Insert(1,99);
_ll->Show();
_ll->Insert(8,333);
_ll->Show();
ElemType del_elem;
_ll->Delete(15,&del_elem);
_ll->Show();
_ll->Destroy();
system("pause");
return 0;
}</span>