- #include<iostream>
- using namespace std;
- class List {
- private :
- int *elem;
- public :
- int length;
- List();
- int Insert(List &L,int i,int e);
- int Delete(List &L,int i,int &e);
- int output(List &L);
- };
- List:: List() {
- elem = new int [10];
- length=0;
- }
- int List::Insert(List &L,int i,int e){
- if(i<1||i>L.length+1)
- cout<<"插入位置异常"<<endl;
- else
- {for(int j=L.length;j>=i;--j)
- L.elem[j]=L.elem[j-1];
- L.elem[i-1]=e;
- length++;}
- return 0;
- }
- int List::Delete(List &L,int i,int &e){
- if(i<1||i>L.length)
- cout<<"删除位置不合法"<<endl;
- else
- {e=L.elem[i-1]; //用e返回
- for(;i<=L.length;++i)
- L.elem[i-1]=L.elem[i];
- --length;
- }
- return 0;
- }
- int List::output(List &L){
- cout<<"表中元素为:"<<endl;
- for(int i=1;i<=L.length;++i)
- cout<<L.elem[i-1]<<" ";
- cout<<endl;
- return 0;
- }
- int main(){
- List L;int x;
- cout<<"表长为:"<<L.length<<endl;
- L.Insert(L,1,2);
- cout<<"表长为:"<<L.length<<endl;
- L.Insert(L,2,3);
- cout<<"表长为:"<<L.length<<endl;
- L.Insert(L,3,4);
- cout<<"表长为:"<<L.length<<endl;
- L.Insert(L,4,5);
- cout<<"表长为:"<<L.length<<endl;
- L.Insert(L,5,6);
- cout<<"表长为:"<<L.length<<endl;
- L.output(L);
- L.Delete(L,5,x);
- cout<<"被删除的元素为:"<<x<<endl;
- L.output(L);
- cout<<"表长为:"<<L.length<<endl;
- getchar();
- return 0;
- }
- //该片段来自于http://www.codesnippet.cn/detail/1811201410997.html
来源: http://www.codesnippet.cn/detail/1811201410997.html