#include<iostream>
#define ERROR 0
#define OK 1
#define MAXSIZE 100
using namespace std;
typedef int Elemtype;
typedef int Status;
typedef struct
{
Elemtype *elem;
int length;
int listsize;
}Sqlist;//控制结构
Status Inin_Sqlist(Sqlist &L)
{
L.elem=new Elemtype[MAXSIZE];
if(!L.elem) return ERROR;
else {
L.listsize= MAXSIZE;
L.length=0;//指针指向
return OK;
}
}
Status Insert_Sqlist(Sqlist &L,int i,Elemtype e)
{
int j;
if(L.length>=L.listsize) {cout<<"move out" << endl; return ERROR;}
if((i<1)||(i>L.length+1)) {cout<<"has erroe"; return ERROR;}
for ( j=L.length-1; j>=i-1; j--)
{
L.elem[j+1]=L.elem[j];
L.elem[i-1]=e;
L.length++;
return OK;
}
}
这个线性表怎么插入不了
这段代码中的问题是在 Insert_Sqlist 函数中。在循环中,L.elem[i-1]=e; 和 L.length++; 应该在循环外面。正确的代码应该是这样的:
Status Insert_Sqlist(Sqlist &L,int i,Elemtype e)
{
int j;
if(L.length>=L.listsize) {cout<<"move out" << endl; return ERROR;}
if((i<1)||(i>L.length+1)) {cout<<"has erroe"; return ERROR;}
for ( j=L.length-1; j>=i-1; j--)
{
L.elem[j+1]=L.elem[j];
}
L.elem[i-1]=e;
L.length++;
return OK;
}