如何建立一个有序顺序表

wjc381160331 2011-09-27 06:46:45
如何建立一个有序顺序表,并实现初始化,球数据元素个数,插入,删除,和取数据元素
...全文
1377 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
尘缘udbwcso 2011-09-27
  • 打赏
  • 举报
回复

#include <stdio.h>
#include <malloc.h>
#define ElemType int
typedef struct
{
ElemType *elem;
int length; //表长度
}ssTable;
/*
*功能:顺序表的创建及初始化
*参数:顺序表中元素个数
*返回值:顺序表的地址
*
*/
ssTable *create(int elemCnt)
{
ssTable *table;
int i;
table = (ssTable*)malloc(sizeof(ssTable));
table->elem = (int*)malloc(sizeof(int)*elemCnt);
printf("输入元素:\n");
table->length = elemCnt;
for(i = 0; i < elemCnt; ++i)
{
scanf("%d", &table->elem[i]);
}
return table;
}
/*
*功能:输出顺序表中元素
*参数:顺序表的地址
*
*/
void display(ssTable *table)
{
int i;
for(i = 0; i < table->length; ++i)
{
printf("%d ", table->elem[i]);
}
printf("\n");
}
/*
*功能:排序,按由小到大
*参数:顺序表的地址
*
*/
void sort(ssTable *table)
{
int i, j;
ElemType tmp;
for(i = 0; i < table->length - 1; ++i)
{
for(j = 0; j < table->length - i - 1; ++j)
{
if(table->elem[j] > table->elem[j+1])
{
tmp = table->elem[j];
table->elem[j] = table->elem[j+1];
table->elem[j+1] = tmp;
}
}
}
}
/*
*功能:插入数据
*参数:要插入的数据,顺序表的地址
*
*/
void insert(ElemType e, ssTable *table)
{
++table->length;
table->elem = (int*)realloc(table->elem, sizeof(int)*table->length);
table->elem[table->length-1] = e;
}

/*
*功能:在顺序表中查找指定的数据
*参数:要查找的数据,顺序表的地址
*返回值:该元素在表中的位置,不存在则返回-1
*
*/
int search(ElemType e, ssTable *table)
{
int i;
for(i = 0; i < table->length; ++i)
{
if(table->elem[i] == e)
return i;
}
return -1;
}


/*
*功能:删除数据
*参数:要删除的数据,顺序表的地址
*
*/
void del(ElemType e, ssTable *table)
{
if(search(e, table) == -1)
return;
ElemType *tmp = (int*)malloc(sizeof(int)*table->length);
int i, j = 0;
for(i = 0; i < table->length; ++i)
{
if(table->elem[i] != e)
tmp[j++] = table->elem[i];
}
table->length = j;
free(table->elem);
table->elem = (int*)malloc(sizeof(int)*table->length);
for(i = 0; i < table->length; ++i)
{
table->elem[i] = tmp[i];
}
free(tmp);
}

int main()
{
ssTable *table;
int elemCnt, find;
ElemType e = 9;
printf("请输入顺序表中元素个数: elemCnt = ");
scanf("%d", &elemCnt);
table = create(elemCnt);
display(table);
sort(table);
display(table);
insert(e, table);
display(table);
find = search(10, table);
if(find == -1)
printf("not found!\n");
else
printf("元素索引为: %d\n", find);
del(9, table);
display(table);
return 0;
}



_了凡_ 2011-09-27
  • 打赏
  • 举报
回复
这个去看任何一本数据结构书吧,不用全看,一般是看第二章,前面5、6页就能搞颠了。

69,382

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧