- 论坛徽章:
- 0
|
//问题:为什么实现不了插入,输不出来?
#include <iostream>
using namespace std;
typedef struct splist{
int *date;
int size;
int maxsize;
}list;
list initlist(list &l)
{
cout<<"请输入初始化顺序表的最大存储数据元素个数:"<<endl;
int a;
cin>>a;
if ((l.date=(int*)malloc(a*sizeof(int)))==NULL)
{
cout<<"分配内存错误\n"<<endl;
exit(1);
}
l.maxsize=a;
l.size=0;
cout<<"请输入元素值,输入0时结束插入操作:"<<endl;
int i;
for (i=0;i<l.maxsize;i++)
{
int a;
cin>>a;
if(a!=0) {l.date=a; l.size++;}
else break;
}
return(l);
}
void outputlist(list *l)
{
cout<<"顺序表为:"<<endl;
int i=0;
while (i<l->size)
{
cout<<l->date<<" ";
i++;
}
cout<<endl;
}
void insertlist(list &l)
{
if(l.size==0) cout<<"顺序表为空"<<endl;
cout<<"请输入元素插入位置:";
int i;
for(;;)
{
cin>>i;
if(i<1||i>l.size) cout<<"输入错误!请重新输入插入位置;";
else break;
}
cout<<"请输入要插入的元素:";
int a,n;
cin>>a;
if (l.size==l.maxsize)
{
l.date=(int*)realloc(l.date,(l.size+10)*sizeof(int));
}
l.size=+1;
l.date[l.size-1]=0;
for (n=l.size-2;n>=i-1;n--) l.date[n+1]=l.date[n];
l.date[i-1]=a;
outputlist(&l);
}
int main()
{
int a,b;
list l;
for( ; ; )
{
cout<<"1.初始化\n";
cout<<"2.插入\n";
cout<<"3.输出\n";
cout<<"Input 1-3: ";
cin>>a;
switch (b=a)
{
case 1: initlist(l);
break;
case 2: insertlist(l);
break;
case 3: outputlist(&l);
break;
default: printf("输入错误!\n");
exit(0);
}
}
return 0;
}
[ 本帖最后由 LK.QQ 于 2009-4-14 14:44 编辑 ] |
|