/* SList.cpp Author: Qiang Xiao Time: 2015-07-11 */ #include<iostream> using namespace std; const int MAX_LENGTH= 20; class SList{ private: int max_len; int arr[MAX_LENGTH]; int len; public: SList(int a[], int len); bool append(int); bool insert(int, int); void sort(); void swap(int*, int*); int getMax(); int getMin(); int getLength() const; void print(); bool pop(); bool remove(int); }; SList::SList(int a[], int leni){ this->max_len= MAX_LENGTH; if(leni< this->max_len+ 1) { for(int i= 0; i< leni; i++){ arr[i]= a[i]; } this->len= leni; } else cout<<"Create Failed!"<<endl; } bool SList::pop(){ if(this->len< 1){ cout<<"Out of range!"<<endl; return false; } this->arr[len-1]= 0; this->len--; return true; } bool SList::remove(int pos){ if(pos< 0 || pos> this->len-1){ cout<<"Out of range!"<<endl; return false; } for(int i= pos; i< this->len; i++){ this->arr[i]= this->arr[i+1]; } this->arr[this->len-1]= 0; this->len--; } int SList::getLength() const{ return this->len; } int SList::getMax() { this->sort(); return this->arr[this->len-1]; } int SList::getMin() { this->sort(); return this->arr[0]; } void SList::swap(int* i, int* j){ int tmp= *i; *i= *j; *j= tmp; } bool SList::insert(int pos, int elem){ if(this->len< this->max_len){ if(pos< 0 || pos> this->max_len || this->len> this->max_len- 1){ cout<<"Out of range."<<endl; return false; } for(int i= this->len; i> pos; i--){ this->arr[i]= this->arr[i- 1]; } this->arr[pos]= elem; this->len++; return true; } } bool SList::append(int elem){ if(this->len< this->max_len){ this->arr[this->len]= elem; len++; return true; } return false; } void SList::sort(){ for(int i= 0; i< this->len; i++){ int min= i; for(int j= i; j< this->len; j++){ if(this->arr[j]< this->arr[min]){ min= j; } } this->swap(&this->arr[min], &this->arr[i]); } this->print(); cout<<endl; } void SList::print(){ for(int i= 0; i< this->len; i++){ cout<<arr[i]<<"\t"; if((i+1)%5== 0) cout<<endl; } } int main(){ cout<<"*****************TEST BEGIN*****************"<<endl; int a[]= {1,10,3,4,9, 11}; int len= sizeof(a)/sizeof(a[0]); SList* s= new SList(a, len); s->print(); cout<<"\n******************************************"<<endl; int item= 30; s->append(item); s->print(); cout<<"\n******************************************"<<endl; int newi= 3000; int pos= 3; s->insert(pos, newi); s->print(); cout<<"\n************After Sort********************"<<endl; s->sort(); cout<<"\n************MAX, MIN & LENGTH*************"<<endl; cout<<"MAX: "<<s->getMax()<<", MIN: "<<s->getMin()<<", LENGTH: "<<s->getLength()<<endl; cout<<"\n*******************POP********************"<<endl; s->pop(); s->print(); cout<<"\n*****************TEST END*****************"<<endl; return 0; }
欢迎交流!
时间: 2024-10-12 03:15:57