实验一:线性表的存储结构与顺序表的存储实现
一、实验内容:编写一个程序实现两个有序(从小到大)顺序表合并成为一个顺序表,合并后的结果放在第一个顺序表中。
二、实验目的:了解并掌握线性表的逻辑结构特性,通过实验掌握顺序存储结构的描述方式及用高级语言进行编程实现的方法。
三、实验代码: #include <iostream> #include <stdio.h> #include <stdlib.h> #define ERROR 0 #define OK 1 #define OVERFLOW -2 #define LIST_INIT_SIZE 100 typedef int Status; typedef int ElemType; typedef struct{ ElemType *elem; int length; int listsize; }SqList; Status InitList_Sq(SqList &L){ L.elem=(ElemType *)malloc(LIST_INIT_SIZE*sizeof(ElemType)); if(!L.elem) exit(OVERFLOW); L.length=0; L.listsize=LIST_INIT_SIZE; return OK; } void Create_Sq(SqList &L){ int i,n; printf("创建一个有序表:\n"); printf("输入有序表中元素的个数:"); scanf("%d",&n); L.length=n; for(i=0;i<n;i++){ printf("输入%d个元素的值:",i+1); scanf("%d",&L.elem[i]); printf("\n"); } } void Disp_Sq(SqList L){ int i,n; n=L.length; for(i=0;i<n;i++) printf("%5d",L.elem[i]); printf("\n"); } void Combine(SqList &La,SqList &Lb){ ElemType *pa,*pb,*pc,*pa_last,*pb_last; pa=La.elem;pb=Lb.elem; SqList Lc; Lc.listsize=Lc.length=La.length+Lb.length; pc=Lc.elem=(ElemType *)malloc(Lc.listsize*sizeof(ElemType)); if(!Lc.elem) exit (OVERFLOW); pa_last=La.elem+La.length -1; pb_last=Lb.elem+Lb.length -1; while(pa<=pa_last&&pb<=pb_last){ if(*pa<*pb) *pc++=*pa++; else *pc++=*pb++; } while(pa<=pa_last) *pc++=*pa++; while(pb<=pb_last) *pc++=*pb++; if(La.listsize<Lc.length) { realloc(La.elem,Lc.length*sizeof(ElemType)); La.listsize=Lc.listsize; } La.length=Lc.length; pa=La.elem; pc=Lc.elem; for(int i=0;i<Lc.length;i++) *pa++=*pc++; } int main(int argc, char** argv) { SqList La,Lb; InitList_Sq(La); InitList_Sq(Lb); Create_Sq(La); Create_Sq(Lb); Disp_Sq(La); Disp_Sq(Lb); Combine(La,Lb); Disp_Sq(La); return 0; 四、实验一结果在PC上显示如下:

文章来源: 线性表的存储结构与顺序表的存储实现