您的位置:首页 > 理论基础 > 数据结构算法

数据结构之线性表

2014-09-26 17:47 288 查看
c语言和c++混合写的,主要是那个清华大学吴伟民,严蔚敏的书,也是这样写的数据结构的 伪代码。

#include
#include
#include
#define ERROR 0
#define SUCCESS 1
#define LIST_INIT_SIZE 10
#define LISTINCREMNT 10
#define SIZE (sizeof(int))

using namespace std;

//
typedef struct
{
int *elem;
int length;
int size;
}SqList;

int InitListSq(SqList&);//初始化线性表
int InsertListSq(SqList&,int i,int e);//在线性表的指定位置i中插入元素e
int DelListSq(SqList&,int i);//删除指定位置i处的元素
void ShowListSq(SqList&,char a[]);//展示所有的元素

int  main()
{

SqList List;
InitListSq(List);
int a[20]={1,-2,3,4,78,-4,-78,-5,-8,-9,45,67,-74,-75,45,-100,-759,-78,456,753};
int j=0;

//用数组元素初始化顺序表
for(;j<20;j++)
{
InsertListSq(List,1,a[j]);
}
InsertListSq(List,1,0);
ShowListSq(List," 初始化表");
return 0;

}

int InitListSq(SqList &L)
{
L.elem=(int*)malloc(LIST_INIT_SIZE*SIZE);
if(!L.elem) return ERROR;
L.length=0;
L.size=LIST_INIT_SIZE;
return SUCCESS;
}

//在顺序线性表L中的第i个位置,i的取值范围为1<=i<=L.length+1
int InsertListSq(SqList &L,int i,int e)
{

int *p,*q;
if(i<1 || i>L.length+1)
{
printf("插入位置有误\n");
return ERROR;
}
if(L.length >= L.size)
{
L.elem=(int*)realloc(L.elem,L.size+LISTINCREMNT*SIZE);
return ERROR;
}

p=L.elem+(i-1);//q为插入位置的地址
q=L.elem+(L.length-1);//p为最后一个元素的地址
for (;q>=p; --q)
*(q+1)=*q;
*p=e;
++L.length;
return SUCCESS;
}

void  ShowListSq(SqList &L,char a[])
{
int i=0;
printf("####show list######\n");
puts(a);
for(;iL.length)
{
printf("删除位置有误\n");
return ERROR;
}
p=L.elem+(i-1);
q=L.elem+(L.length-1);
for(;q>=p;p++)
{

*p=*(p+1);
}
*q=NULL;
--L.length;
return SUCCESS;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息