验证性实验一Word下载.docx
《验证性实验一Word下载.docx》由会员分享,可在线阅读,更多相关《验证性实验一Word下载.docx(15页珍藏版)》请在冰豆网上搜索。
stdio.h>
string.h>
conio.h>
iostream.h>
malloc.h>
#defineLIST_INIT_SIZE10
#defineOK1
#defineERROR0
#defineLISTINCREMENT10
typedefintElemType;
typedefstruct
{int*elem;
intlength;
intlistsize;
}SqList;
intInitList_Sq(SqList&
L)//InitList_Sq()function
{//InititialaSq_List
L.elem=(ElemType*)malloc(LIST_INIT_SIZE*sizeof(ElemType));
if(!
L.elem)return(0);
L.length=0;
L.listsize=LIST_INIT_SIZE;
return
(1);
}//endofInitList_Sq()function
intListInsert_sq(SqList&
L,inti,inte)//ListInsert_sq()
{if(i<
1||i>
L.length+1)//i(location)isillegal
{cout<
<
"
Initialfailure!
endl;
getch();
return(ERROR);
}
if(L.length>
=L.listsize)//insertintotheendoftheSqlist
{int*Newbase;
Newbase=(int*)realloc(L.elem,(L.listsize+LISTINCREMENT)*sizeof(int));
if(!
Newbase)
{cout<
Overflow!
getch();
return(ERROR);
L.elem=Newbase;
L.listsize+=LISTINCREMENT;
int*p,*q;
q=&
(L.elem[i-1]);
//qpointattheelementbeforetheinsertedone
for(p=&
(L.elem[L.length-1]);
p>
=q;
--p)//movetheelement
*(p+1)=*p;
*q=e;
++L.length;
return(OK);
}//ListInser_sq()end
voidmain()
{intm,i,x;
SqListA;
InitList_Sq(A);
cout<
InputthesizeofA:
\n"
cin>
>
m;
cout<
InputtheelementofA:
;
for(i=1;
i<
=m;
i++)
{cin>
x;
ListInsert_sq(A,i,x);
}
cout<
TheelementofA:
for(i=0;
A.length;
cout<
A.elem[i]<
'
\t'
实验结果:
实验结果分析:
本程序中首先定义了一个链表的结构体,然后定义了一个线性表,在插入函数中先申请了一个与头文件中定义的线性表大小相同的内存空间,然后用if语句判断这个线性表是否存在,若不存在则返回0,若存在则将线性表的长度设置为与申请的空间大小相同。
然后就定义了输入和输出函数。
在主函数中首先定义了两个变量,接着定义了一个线性表,然后调用见线性表的函数、输入函数和输出函数。
最后运行程序就得到了如上图的结果。
(二)已知顺序表la和lb中的数据元素按非递减有序排列,将la和lb表中的数据元素,合并成为一个新的顺序表lc,lc中的数据元素仍按非递减有序排列,并且不破坏la和lb表。
#defineMAXSIZE20
#defineLIST_INIT_SIZE20
#defineLISTINCREMENT20
#defineTRUE1
#defineFALSE0
L.elem=(int*)malloc(LIST_INIT_SIZE*sizeof(int));
L,inti,ElemTypee)//ListInsert_sq()
Newbase=(ElemType*)realloc(L.elem,(L.listsize+LISTINCREMENT)*sizeof(ElemType));
intMerge_Sq(SqList&
A,SqList&
B,SqList&
C)//Merge_Sq()function
{//MergetheSqListAandBtoC
C.listsize=C.length=A.length+B.length;
C.elem=(ElemType*)malloc(C.listsize*sizeof(ElemType));
inti=0,j=0;
//iandjistheSubscriptofA.elem[]andB.elem[]
intk=0;
//kistheSubscriptofC.elem[]
while(i<
=A.length)//inserttherestofSqListA
{C.elem[k]=A.elem[i];
i++;
k++;
}//endofwhile
while(j<
=B.length)//inserttherestofSqListB
{C.elem[k-1]=B.elem[j];
j++;
SuccesstoMergeAandB!
return
(1);
}//endofMerge_Sq()function
voidmain()
{SqListA,B,C;
intm,n,i,j,x;
InitList_Sq(A);
InitList_Sq(B);
InputthesizeofB:
n;
InputtheelementofB:
for(j=1;
j<
=n;
j++)
{cin>
ListInsert_sq(B,j,x);
}
InitList_Sq(C);
Merge_Sq(A,B,C);
Aftermerge,theelementofC:
for(i=0;
m+n;
C.elem[i]<
}
结果分析:
创建了一个SqList的结构体函数和创建线性表的函数,然后是输入函数,使用for循环来将数字逐个输入,显示的很清楚用户输入的是第几个数字。
用Merge_Sq函数来实现两表的合并,用cout输出。
(三).从有序顺序表A中删除那些在顺序表B和顺序表C中都出现的元素
#defineOK1
#defineERROR0
#defineMAXSIZE10
/*顺序存储类型*/
/*构造一个空线性表算法*