您的位置:首页 > 其它

顺序表1.2

2016-04-09 15:46 316 查看
编写一个程序,动态地创建一个顺序表。要求:顺序表初始长度为10,向顺序表中输入15个整数,并打印出来;再删除顺序表中的第5个元素,打印出删除后的结果。

注意:

realloc的用法:动态内存调整

指针名=(数据类型*)realloc(要改变内存大小的指针名,新的大小)。

头文件:#include <stdlib.h> 有些编译器需要#include <malloc.h>,在TC2.0中可以使用alloc.h头文件

#include"stdio.h"

//#include"conio.h"

#include<malloc.h>

#define maxsize 10

typedef int elemtype;

typedef struct {

elemtype *elem;

int length;

int listsize;

}sqlist;

void initsqlist(sqlist *L)

{

L->elem = (int *)malloc(maxsize*sizeof(elemtype));

if (!L->elem)

{

printf("initsqlist failed\n");

return ;

}

L->length = 0;

L->listsize = maxsize;

}

void Insertelem(sqlist *L, int i, elemtype item)

{

elemtype *base, *insertPtr, *p;

if (i<1 || i>L->length + 1) //因为这是插入,所以i可以等于L->length,就是插到了最后一个的后面,但是删除 的时候i不可以等于L->length;

{

printf("insertelem failed\n");

return ;

}

if (L->length >= L->listsize)

{

base = (elemtype*)realloc(L->elem, (L->listsize + 10)*sizeof(elemtype));

L->elem = base;

L->listsize = L->listsize + 10;

}

insertPtr = &(L->elem[i - 1]);

for (p = &(L->elem[L->length - 1]); p >= insertPtr; p--)

*(p + 1) = *p;

*insertPtr = item;

L->length++;

}

void DelElem(sqlist *L, int i)

{

elemtype *delitem, *q;

if (i<1 || i>L->length)

{

printf("delelem failed\n");

return;

}

delitem = &(L->elem[i-1]);

q = &(L->elem[L->length - 1]);

for (delitem; delitem <= q; delitem++)

*(delitem) = *(delitem+1);

L->length--;

}

int main()

{

sqlist l;

int i;

initsqlist(&l);

for (i = 0; i < 15; i++)

Insertelem(&l, i + 1, i + 1);

printf("\nthe const of the list is\n");

for (i = 0; i < l.length; i++)

printf("%d ", l.elem[i]);

DelElem(&l, 5);

printf("\ndelete the fifth element\n");

for (i = 0; i < l.length; i++)

printf("%d ", l.elem[i]);

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: