求一个c++的建立线性表最简单的程序,要能运行的

2024-12-02 22:35:03
推荐回答(2个)
回答1:

#include
#include
#include
const LIST_INIT_SIZE=10;
const LISTINCREMENT=1;
typedef struct
{
int *elem;
int length;
int listsize;
}SqList;
void InitList_Sq(SqList&L)
{
L.elem=(int*)malloc(LIST_INIT_SIZE*sizeof(int));
if(!L.elem)
exit(0);
L.length=10;
L.listsize=LIST_INIT_SIZE;
cout<<"OK!"<}
void ListInsert_Sq(SqList&L,int i,int e){
if(i<1||i>L.length+1)
cout<<"ERROR!"< if(L.length>=L.listsize)
{
int *newbase=(int*)realloc(L.elem,(L.listsize+LISTINCREMENT)*sizeof(int));
if(!newbase)
exit(0);
L.elem=newbase;
L.listsize+=LISTINCREMENT;
}
int *q=&(L.elem[i-1]);
for(int*p=&(L.elem[L.length-1]);p>=q;--p)
*(p+1)=*p;
*q=e;
++L.length;
cout<<"OK!"<}
void ListDelete_Sq(SqList&L,int i,int&e)
{
if((i<1)||(i>L.length))
cout<<"ERROR!"< int *p=&(L.elem[i-1]);
e=*p;
cout< int *q=L.elem+L.length-1;
for(++p;p<=q;++p)*(p-1)=*p;
--L.length;
cout<<"OK!"<}
bool compare(int m,int n)
{
if(m==n)
return true;
else
return false;
}
void LocateElem_Sq(SqList L,int e){
int i=1;
int *p=L.elem;
while(i<=L.length&&!compare(*p++,e))
++i;
if(i<=L.length)
cout< else
cout<<"ERROR"<}
void disp(SqList&L)
{
int *p=L.elem;
for(int i=0;i {
cout<<*p<<"\t";
p++;
}
}
int main()
{
SqList List;
InitList_Sq(List);
cout<<"请为线性表设置初值"< int *p=List.elem,a,i,e,E;
for(i=0;i {
cin>>a;
*p=a;
p++;
}
cout<<"请输入要插入元素的位置与元素的值"< cin>>i>>e;
ListInsert_Sq(List,i,e);
cout<<"插入元素后的线性表为"< disp(List);
cout<<"请输入要删除元素的位置"< cin>>i;
ListDelete_Sq(List,i,E);
cout<<"删除元素后的线性表为"< disp(List);
cout<<"请输入要查找元素的值"< cin>>e;
LocateElem_Sq(List,e);
return 0;
}
给分给分

回答2:

你用的是什么书,支图书馆找有例子的书。