您的位置:首页 > 其它

线性表初始化插入消毁

2009-03-13 11:10 169 查看
#include "stdio.h"
#include "iostream.h"
#include "malloc.h"
typedef struct
{
int no;
int grade;
}ElemType;
typedef struct
{
ElemType *elem;
int CurrentLength;
int MaxSize;
}SqList;
void InitList(SqList *pL)
{
pL->MaxSize = 10;
pL->elem = (ElemType*)malloc(pL->MaxSize*sizeof(ElemType));
/*上句为pL->elem 申请pL->MaxSize个ElemType结构体所请求的内存空间,若成功返回
一个ElemType结构体类型的指针,并存入pL->elem变量中*/
pL->CurrentLength=0;
}
void DestroyList(SqList *pL)
{
free(pL->elem); /*释放内存空间*/
}
int ListInsert(SqList *pL,ElemType e)
{
int i,j;
if (pL->CurrentLength>=pL->MaxSize)
{
pL->MaxSize = pL->CurrentLength + 10;
pL->elem = (ElemType *)realloc(pL->elem,(pL->MaxSize)*sizeof(ElemType));
/*上句为pL->elem 重新申请内存空间*/
}

/*找插入点的位置*/
for(i=0;i<pL->CurrentLength;i++)
{
if (e.grade>pL->elem[i].grade)
break;
}

/*向后移动数据*/
for(j=pL->CurrentLength+1;j>i;j--)
pL->elem[j]=pL->elem[j-1];

pL->elem[i]=e;

pL->CurrentLength=pL->CurrentLength+1;
return 1;
}
void ShowList(SqList*pL)
{
int i;
for(i=0;i<pL->CurrentLength;i++)
{
printf("\n(%d,%d)",pL->elem[i].no,pL->elem[i].grade);
printf("\n");
}
}
void main()
{
SqList L;
ElemType e;
InitList(&L);
e.no=1;e.grade=85;
ListInsert(&L,e);
e.no=2;e.grade=80;
ListInsert(&L,e);
e.no=3;e.grade=70;
ListInsert(&L,e);
e.no=1;e.grade=85;
ListInsert(&L,e);
e.no=2;e.grade=80;
ListInsert(&L,e);
e.no=3;e.grade=70;
ListInsert(&L,e);
e.no=1;e.grade=85;
ListInsert(&L,e);
e.no=2;e.grade=80;
ListInsert(&L,e);
ShowList(&L);
DestroyList(&L);
}

在VC6 WINDOWS XP2 下编译通过 结果如下:

(1,85)
(1,85)
(1,85)
(2,80)
(2,80)
(2,80)
(3,70)
(3,70)
Press any key to continue

这是为什么呢
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐