主题:顺序表的建立插入删除查找课程设计
小渡渡鸟
[专家分:0] 发布于 2007-12-26 22:09:00
谁能给我发个c++程序,能够实现顺序表的建立插入删除查找功能.救命。。
死掉了。。文科大四了突然学C++一岗。。
回复列表 (共2个回复)
沙发
恋颖2008 [专家分:0] 发布于 2008-12-16 21:55:00
#include <stdio.h>
#include <stdlib.h>
#define OK 1
#define ERROR 0
#define OVERFLOW -1
typedef int ElemType;
typedef int Status;
#define LIST_INIT_SIZE 100
#define LISTINCREMENT 10
typedef struct{
ElemType *elem;
int length;
int listsize;
}SqList;
Status InitList_Sq(SqList *L){
int i,n;
L->elem = (ElemType * )malloc(LIST_INIT_SIZE*sizeof(ElemType));
if (! L->elem) exit (OVERFLOW);
printf("您希望您的线性表有几个元素: ");
scanf("%d",&n);
printf("\n");
printf("输入您的%d个元素,以构建顺序表: \n",n);
for(i=1;i<=n;i++)
scanf("%d",&L->elem[i-1]);
L->length = n;
L->listsize = LIST_INIT_SIZE;
return OK;
}//InitList_Sq
Status PrintList_Sq(SqList L){
int i;
printf("顺序表中的元素为: ");
for (i=1;i<=L.length;i++)
printf("%d ",L.elem[i-1]);
printf("\n");
return OK;
}//PrintList_Sq
Status ListInsert_Sq(SqList *L, int i ,ElemType e){
ElemType *p,*q;
if (i<1 || i>L->length+1) return ERROR;
if (L->length >=L->listsize){
L->elem = (ElemType * )realloc(L->elem,(L->listsize + LISTINCREMENT) * sizeof (ElemType));
if (!L->elem )exit(OVERFLOW);
L->listsize += LISTINCREMENT;
}
q = & (L->elem[i-1]);
for (p = & (L->elem[L->length - 1]);p>=q;--p)*(p+1) = *p;
*q = e ;
++L->length ;
return OK ;
}//ListInsert_Sq
Status LocateElem_Sq(SqList L, ElemType e){
int i=1;
ElemType *p;
p =L.elem;
while (i<=L.length && !(*p++==e)) ++i;
if (i<=L.length) return i;
else return 0;
}
Status ListDelete_Sq(SqList *L,int i){
ElemType e,*p,*q;
if((i<1)||(i>L->length)) return ERROR;
p=&(L->elem[i-1]);
e=*p;
q=L->elem+L->length-1;
for(++p;p<=q;++p)
*(p-1)=*p;
--L->length;
printf("%3d\n",e);
return OK;
}
void main(){
SqList L;
ElemType k,e;
int i,j,m;
if (InitList_Sq(&L)==OVERFLOW)
printf("分配失败,退出程序!");
printf("输出程序中的元素\n");
PrintList_Sq(L);
printf("\n请输入所需插入的位置和您要插入的元素:");
printf("\ninput i,e=");
scanf("%d%d",&i,&e);
if (ListInsert_Sq(&L,i,e)!=OK) printf("i值不合法或当前存储空间以满\n");
else PrintList_Sq(L);
printf("\n");
printf("请输入您要查找的元素:");
scanf("%d",&k);
m=LocateElem_Sq ( L,k);
if(m)
printf("\n您要查找的元素是这个线形表的第%d个元素\n",m);
else printf("对不起,该线形表中不存在这个元素\n");
printf("\n请输入要删除的第几个元素:j=");
scanf("%d",&j);
printf("\n");
if (ListDelete_Sq(&L,j)!=OK)
printf("删除失败!");
else PrintList_Sq(L);
printf("\n");
}
我来回复