数据结构之顺序表的静态表示和动态表示

时间:2022-05-18 10:28:30

顺序表的静态表示,代码如下:

#include <stdio.h>

#define MAXSIZE			100

void insertElem(int *Sqlist, int *len, int i, int x);
void deleteElem(int *Sqlist, int *len, int i);

int main()
{
	int Sqlist[MAXSIZE];
	int i;
	int len;
	for(i = 0; i < 6; ++i)
		scanf("%d",&Sqlist[i]);
	len = 6;
	for(i = 0; i < len; ++i)
		printf("%d ",Sqlist[i]);
	printf("The spare space is %d\n",MAXSIZE - len);
	insertElem(Sqlist, &len,  3, 0);
	for(i = 0; i < len; ++i)
		printf("%d ",Sqlist[i]);
	printf("The spare space is %d\n",MAXSIZE - len);
	deleteElem(Sqlist,&len,11);
	for(i = 0; i < len; ++i)
		printf("%d ",Sqlist[i]);
	printf("The spare space is %d\n",MAXSIZE - len);
	return 0;
}

void insertElem(int *Sqlist, int *len, int i, int x)
{
	int t;
	if(i < 1 || i > *len + 1 || *len == MAXSIZE)
	{
		printf("This insert is illegal.\n");
		return ;
	}
	for(t = *len - 1; t >= i - 1; --t)
		Sqlist[t + 1] = Sqlist[t];
	Sqlist[i - 1] = x;
	*len = *len + 1;
}

void deleteElem(int *Sqlist, int *len, int i)
{
	int j;
	if(i < 1 || i > *len)
	{
		printf("This delete is illegal.\n");
		return ;
	}
	for(j = i; j <= *len - 1; j++)
		Sqlist[j - 1] = Sqlist[j];
	*len = *len - 1;
}
顺序表的动态表示,代码如下:

#include <stdio.h>
#include <stdlib.h>

#define LIST_INIT_SIZE		10
#define LISTINCREMENT		10

typedef struct{
	int *elem;
	int length;
	int listsize;
}Sqlist;
void initSqlist(Sqlist &L);
void insertElem(Sqlist &L, int i, int x);
void deleteElem(Sqlist &L, int i);

int main()
{
	Sqlist L;
	int i;
	initSqlist(L);
	for(i = 0; i < 15; i++)
		insertElem(L, i + 1, i + 1);
	printf("\nThe content of list is\n");
	for(i = 0; i < L.length; i++)
		printf("%d ",L.elem[i]);
	deleteElem(L,5);
	printf("\nDelete the fifth element\n");
	for(i = 0; i < L.length; i++)
		printf("%d ",L.elem[i]);
	return 0;
}

void initSqlist(Sqlist &L)
{
	L.elem = (int*)malloc(LIST_INIT_SIZE * sizeof(int));
	if(!L.elem)
		exit(0);
	L.length = 0;
	L.listsize = LIST_INIT_SIZE;
}

void insertElem(Sqlist &L, int i, int x)
{
	int *base,*p,*q;
	if(i < 1 || i > L.length + 1)
		exit(0);
	if(L.length >= L.listsize)
	{
		base = (int*)realloc(L.elem,(L.listsize + LISTINCREMENT) * sizeof(int));
		if(!base)
			exit(0);
		L.elem = base;
		L.listsize += LISTINCREMENT;
	}
	q = &(L.elem[i - 1]);
	for(p = &L.elem[L.length - 1]; p >= q; --p)
		*(p + 1) = *p;
	*q = x;
	L.length++;
}

void deleteElem(Sqlist &L, int i)
{
	int *p;
	if(i < 1 || i > L.length)
		exit(0);
	for(p = &L.elem[i]; p <= &(L.elem[L.length - 1]); p++)
		*(p - 1) = *p;
	L.length--;
}