数据结构顺序表问题 求解 !!!
请求大虾们帮助!!程序在C++6.0中调试没有错误,但是运行却输出不了正确结果,输出的错误结果如下:
i值不合法
i值不合法
i值不合法
i值不合法
La=
i值不合法
i值不合法
i值不合法
i值不合法
Lb=
Lc=
不知道是程序运行的哪一部分出错,我对了很多遍代码了都不知道什么问题!!
#include<string.h>
#include<ctype.h>
#include<malloc.h>
#include<limits.h>
#include<stdio.h>
#include<stdlib.h>
#include<io.h>
#include<math.h>
#include<process.h>
#include<iostream.h>
#define TRUE 1
#define define FALSE 0
#define OK 1
#define ERROR 0
#define INFEASIBLE 1
typedef int Status;
typedef int Boolean;
typedef int ElemType;
#define LIST_INIT_SIZE 100 // 线性表存储空间的初始分配量
#define LISTINCREMENT 10 // 线性表存储空间的分配增量
typedef struct
{
ElemType *elem; // 存储空间基址
int length; //当前表的长度
int listsize; //当前分配的存储容量(以sizeof(ElemType)为单位)
}SqList;
Status InitList(SqList &L)
{ // 构造一个空的顺序线性表
L.elem=(ElemType *)malloc(LIST_INIT_SIZE*sizeof(ElemType));
if(!L.elem)
exit(OVERFLOW); // 存储分配失败
L.length=0; // 空表长度为0
L.listsize=LIST_INIT_SIZE; // 初始存储容量
return OK;
}
void ListTraverse(SqList &L)
{ // 初始条件:顺序线性表L已存在
// 操作结果:依次输出L的每个数据元素
ElemType *p;
int i;
p=L.elem;
for(i=1;i<=L.length;i++)
printf("%5d",*p); p++;
printf("\n");
}
Status ListInsert(SqList &L,int i,ElemType e)
{ // 初始条件:顺序线性表L已存在,i的合法值: 1≤i≤ListLength(L)+1
// 操作结果:在L中第i个位置之前插入新的数据元素e,L的长度加1
ElemType *newbase,*q,*p;
if(i<1||i>L.length+1){
printf("i值不合法\n");
return ERROR;
}
if(L.length>=L.listsize) // 当前存储空间已满,增加分配
{
newbase=(ElemType *)realloc(L.elem,(L.listsize+LISTINCREMENT)*sizeof(ElemType));
//重新分配内存快
if(!newbase)
exit (OVERFLOW); // 存储分配失败
L.elem=newbase; // 新基址
L.listsize+=LISTINCREMENT; // 增加存储容量
}
q=&(L.elem[i-1]); // q为插入位置
for(p=&(L.elem[L.length-1]);p>=q;--p) // 插入位置及之后的元素右移
{*(p+1)=*p;
*q=e; // 插入e
++L.length; }// 表长增1
return OK;
}
Status GetElem (SqList &L,int i,ElemType &e)
{ // 初始条件:顺序线性表L已存在,1≤i≤ListLength(L)。操作结果:用e返回L中第i个数据元素的值
if(i<1||i>L.length)
return ERROR;
e=*(L.elem+i-1);//e=L.elem[i-1];
return OK;
}
Status ListLength(SqList &L)
{
return L.length;
}
void MergeList(SqList La,SqList Lb,SqList &Lc)
{ ElemType ai,bj;
int i=1,j=1,k=0, La_len, Lb_len; //i,j开始分别指向La,Lb的 //第一个元素
InitList(Lc); //创建空表Lc
La_len=ListLength(La);
Lb_len=ListLength(Lb);
while((i<=La_len)&&(j<=Lb_len)) // La和Lb均非空
{ GetElem(La,i,ai);
GetElem(Lb,j,bj);
if(ai<=bj){ListInsert(Lc, ++k, ai); ++i;}
else{ListInsert(Lc, ++k, bj); ++j;}
}
while(i<=La_len) //说明表Lb已经为空了,只需将La中剩下的
//元素插入Lc中了。
{
GetElem(La,i++,ai);
ListInsert(Lc,++k,ai);
}
while(j<=Lb_len) //说明表La已经为空了,只需将Lb中剩下的
//元素插入Lc中了。
{
GetElem(Lb,j++,bj);
ListInsert(Lc,++k,bj);
}
}
void main()
{ SqList La,Lb,Lc;
int j;
InitList(La); // 创建空表La
for(j=1;j<=5;j++) // 在表La中插入5个元素,依次为1、2、3、4、5
ListInsert(La,j,j);
printf("La= "); // 输出表La的内容
ListTraverse(La);
InitList(Lb); // 创建空表Lb
for(j=1;j<=5;j++) // 在表Lb中插入5个元素,依次为2, 4, 6, 8, 10
ListInsert(Lb,j,2*j);
printf("Lb= "); // 输出表Lb的内容
ListTraverse(Lb); // 由按非递减排列的表La、Lb得到按非递减排列的表Lc
MergeList(La,Lb,Lc);
printf("Lc= "); //输出表Lc的内容
ListTraverse(Lc);
}
[解决办法]