写了一个线性表顺序存储,总结一点经验
#include "stdafx.h"
typedef int ElemType;
typedef struct
{
ElemType *elem;//这是定义的指向数据类型的指针,操纵指针的地址来指向数据元素
int length; //数据元素的长度
int listsize; //分配的存储大小 以查看是否满足存储数据的需要
}SqList;
//
void InitList(SqList &L,int listsize)
{
L.elem=(ElemType*)malloc(listsize*sizeof(ElemType));
L.length=0;
L.listsize=listsize;
}
int InsertList(SqList &L,int i,int e)
{//insert element e to list L at i;
if(i<0||i>L.length)
{
printf("error position");
return 0;
}
if(L.listsize<L.length)
{
L.elem=(ElemType*)realloc(L.elem,(10+5)*sizeof(ElemType));
L.listsize+=5;
}
for(int j=L.length;j>i;j--)
{
L.elem[j]=L.elem[j-1];
}
L.elem[i]=e;
L.length++;
return 1;
}
//
int DeleteElem(SqList &L,int i)
{//delete the element at the position i;
if(i<0||i>L.length)
{
printf("error position");
return 0;
}
if(i==L.length)
L.length--;
else
{
for(int j=i;j<L.length-1;j++)
{
L.elem[j]=L.elem[j+1];
}
L.length--;
}
return 1;
}
int _tmain(int argc, _TCHAR* argv[])
{
int a[5]={1,2,3,4,5};
SqList list;
InitList(list,10);
for(int i=0;i<5;i++)
{
InsertList(list,i,i+1);
cout<<list.elem[i];
}
cout<<endl;
InsertList(list,5,0);
for(int i=0;i<6;i++)
{
cout<<list.elem[i];
}
DeleteElem(list,3);
cout<<endl;
for(int i=0;i<5;i++)
{
cout<<list.elem[i];
}
cout<<endl;
}