《数据结构、算法与应用》第五章41题``
#ifndef INSERT_H_INCLUDED
#define INSERT_H_INCLUDED
#include<iostream>
#include<iterator>
#include<algorithm>
using namespace std;
class arrayList
{
public:
arrayList(){}
arrayList(int* num,int* fr,int* la);
~arrayList() {}
void insert_1(int i,int index,int data);
void show(int index);
void show_list();
protected:
int* element;
int* front_1;
int* last_1;
};
arrayList::arrayList(int* num,int* fr,int* la):element(num),front_1(fr),last_1(la){};
void arrayList::insert_1(int i,int index,int data)
{
cout<<endl;
int size_1;
size_1=*(last_1+i)-*(front_1+i);
if(index<0||index>size_1)
{
cout<<"index out of range!";
return;
}
for(int i=0;i<=4;++i)
{
cout<<"front["<<i<<"]:"<<*(front_1+i)<<" ";
cout<<"last["<<i<<"]:"<<*(last_1+i)<<endl;
}
cout<<endl;
for(int j=i;j<4;++j)//遍历当前子数组到最右子数组,j只是临时的,不能多用
if(*(last_1+j)<*(front_1+j+1))//判断所遍历的子数组是否有空间
{
for(int k=0;k<j-i;++k)//先向右移动整块数组的个数
{
for(int l=0;l<*(last_1+j)-*(front_1+j);++l)//移动满数组的所有元素个数
element[*(last_1+j)+1-l]=element[*(last_1+j)-l];
++(*(front_1+j));
++(*(last_1+j));
}
if(*(last_1+i)==*(front_1+i))
{
++(*(last_1+i));
element[*(last_1+i)]=data;
cout<<endl;
for(int i=0;i<=4;++i)
{
cout<<"front["<<i<<"]:"<<*(front_1+i)<<" ";
cout<<"last["<<i<<"]:"<<*(last_1+i)<<endl;
}
cout<<endl;
return;
}
for(int l=0;l<*(last_1+i)-(*(front_1+i)+index+1)+1;++l)//再向右复制挪动I数组index右侧的剩余元素
element[*(last_1+i)+1-l]=element[*(last_1+i)-l];
element[*(front_1+i)+index+1]=data;//插入元素
++(*(last_1+i));
cout<<endl;
for(int i=0;i<=4;++i)
{
cout<<"front["<<i<<"]:"<<*(front_1+i)<<" ";
cout<<"last["<<i<<"]:"<<*(last_1+i)<<endl;
}
cout<<endl;
return;
}
for(int j=i;j>1;--j)//遍历第1个数组到左侧数组,j只是临时的,不能多用
if(*(last_1+j-1)<*(front_1+j))//判断所遍历的子数组是否有空间
{
for(int k=0;k<i-j;++k)//先向左移动整块数组的个数
{
for(int l=0;l<*(last_1+j)-*(front_1+j);++l)//移动满数组的所有元素个数
element[*(front_1+j)]=element[*(front_1+j)+l];
--(*(front_1+j));
--(*(last_1+j));
}
for(int l=0;l<index+1;++l)//再向右复制挪动I数组index右侧的剩余元素
element[*(front_1+i)+l]=element[*(front_1+i)+1+l];
element[*(front_1+i)+index+1]=data;//插入元素
--(*(front_1+i));
cout<<endl;
for(int i=0;i<=4;++i)
{
cout<<"front["<<i<<"]:"<<*(front_1+i)<<" ";
cout<<"last["<<i<<"]:"<<*(last_1+i)<<endl;
}
cout<<endl;
return;
}
cout<<"没有空间以插入数据!\n";//为方便调试没有抛出异常
return;
}
void arrayList::show(int index)
{
cout<<"The "<<index<<"th array:";
copy(element+(*(front_1+index)+1),element+(*(last_1+index)+1),ostream_iterator<int,char>(cout," "));
cout<<endl;
}
void arrayList::show_list()
{
cout<<"List all the array:\n";
for(int i=1;i<4;i++)
show(i);
}
#endif // INSERT_H_INCLUDED