基于数组的列表实现

来源:互联网 发布:手机淘宝怎样发送链接 编辑:程序博客网 时间:2024/06/17 15:53
//--------List.h----------#include<iostream>#ifndef LIST#define LISTconst int CAPACITY=1024;typedef int ElementType;class List{public:List();bool empty() const;void insert(ElementType item,int pos);void erase(int pos);void display(ostream & out) const;private:    int mySize;ElementType myArray[CAPACITY];};ostream & operator<<(ostream & out,const List & aList);#endif

//-------List.cpp----------#include<cassert>using namespace std;#include"List.h"List::List():mySize(0){}bool List::empty() const{return mySize==0;}void List::display(ostream & out) const{for(int i=0;i<mySize;i++)out<<myArray[i]<<" ";}ostream & operator<<(ostream & out,const List & aList){aList.display(out);return out;}void List::insert(ElementType item,int pos){if(mySize==CAPACITY){ cerr<<"***No space for list element.***\n";exit(1);}if(pos<0||pos>mySize){cerr<<"***Illegal location to insert.***\n";return;}for(int i=mySize;i>pos;i--)myArray[i]=myArray[i-1];myArray[pos]=item;mySize++;}void List::erase(int pos){if(mySize==0){cerr<<"***List is empty.***\n";return;}if(pos<0||pos>=mySize){cerr<<"***Illegal location to delete***.\n";return;}for(int i=pos;i<mySize;i++)myArray[i]=myArray[i+1];  mySize--;}

//------------main.cpp------------#include<iostream>using namespace std;#include"List.h"int main(){List intList;cout<<"Construction intList\n";if(intList.empty())cout<<"Empty List:  \n"    <<intList<<endl;for(int i=0;i<10;i++){cout<<"Inserting "<<i<<"at position "<<i/2<<endl;intList.insert(i,i/2);cout<<intList<<endl;}cout<<"List empty? "<<(intList.empty() ? "Yes":"No")<<endl;    cout<<"\nTry to insert at position -1"<<endl;    intList.insert(0,-1);    cout<<"\nTry to insert at position -1"<<endl;    intList.insert(0,10);int index;cout<<endl;    while(!intList.empty())    {         cout<<"Give an index of a list element to remove: ";         cin>>index;         intList.erase(index);         cout<<intList<<endl;    }    cout<<"List is empty"<<endl;    cout<<"\nInserting "<<CAPACITY<<"integers\n";    for(int i=0;i<CAPACITY;i++)    intList.insert(i,i);    cout<<"Attempt to insert one more integers:\n";    intList.insert(-1,0);}

原创粉丝点击