一、顺序表

  定义一张顺序表就是在内存中开辟一段连续的存储空间,并给他取个名字。

定义顺序列表的方法:一、静态定义;二、动态定义;

静态定义

#define MaxSize 100
ElemType Sqlist[MaxSize];
int len;

动态定义

#define MaxSize 100
typedef struct{
ElemType *elem;
int length;
int listsize;
} Sqlist;
void initSqlist(Sqlist *L)
{
L->elem = (int *)malloc(MaxSize*sizeof(ElemType));
if (!L->elem)
{
exit(0);
}
L->length = 0;
L->listsize = Maxsize;
}

像顺序表中插入元素

    在长度为n的顺序表中的第i个位置插入新元素。例如:

    A(a1,a2,...ai-1,ai,...an)

    在第i个位置插入新元素item后,变为

    A (a1,a2,...ai-1,item.ai,... an)

静态表中插入:

void InserElem(ElemType Sqlist[], int n, int i, ElemType item)
{
int t;
if (n==MaxSize || i<1 || i>n+1)
{
exit(0);
}
for (t=n-1; t>=i-1; t--)
{
Sqlist[t+1] = Sqlist[t];
}
Sqlist[i-1] = item;
n = n + 1;
}

 

  动态表中插入

 

void InsertElem(Sqlist *L, int i, ElemType item)
{
ElemType *insertPtr, *p;
if(i<1 || i>L->length+1)
{
exit(0);
}
if(L->length > L->listsize)
{
L->elem = (ElemType *)realloc(L->elem, (L->listsize+10)*sizeof (ElemType));
L->listsize = L->listsize + 10;
}
insertPtr = &(L->elem[i-1];
for (p=&(L->elem[L->length-1]); p>=inserPtr; p--)
{
*(p+1) = *p;
}
*insertPrt = item;
L->length++;
}

 

 

posted @ 2012-02-15 19:26  Mr.阿拉丁  阅读(850)  评论(0编辑  收藏  举报