#include using namespace std; typedef int DATA; const unsigned npos=(unsigned)-1; class clink{ struct node{ DATA d; node* next; node( const DATA& cd ) :d(cd), next(NULL) {} }; node* head; int len; public: clink():head(NULL),len(0){} ~clink(){ clear(); } node* & getp( unsigned pos ){ if( pos==0 || head==NULL ) return head; node* p = head; for( int i=1; i next ) p = p->next; else break; } return p->next; } void insert( const DATA& cd, unsigned pos=0 ){ node* & lp = getp( pos ); node* np = new node( cd ); np->next = lp; lp = np; len++; } friend ostream& operator<<( ostream& os, const clink& cc ) { os << "{ "; node* p = cc.head; while( p ){ os << p->d << ' '; p = p->next; } os << "} "; return os; } unsigned find( const DATA& cd ){ node* p = head; unsigned pos=0; while( p ){ if( p->d==cd ) return pos; pos++; p = p->next; } return npos; } bool update( const DATA& d1, const DATA& d2 ){ unsigned pos=find( d1 ); node* p; if( pos==npos ) return false; p = getp( pos ); p->d = d2; return true; } bool erase( const DATA& cd ){ unsigned pos=find( cd ); node* p; if( pos==npos ) return false; node* & lp = getp( pos ); p = lp; lp = lp->next; delete p; len--; return true; } int size(){ return len; } bool empty(){ return head==NULL; } void clear(){ node* p; while( head ){ p = head->next; delete head; head = p; } len = 0; } }; int main() { clink ol; cout << ol << endl; ol.insert( 10 ); ol.insert( 20, npos ); ol.insert( 30, 0 ); ol.insert( 40 ); ol.insert( 50, 1 ); cout << ol << endl; DATA d; cout << "input a DATA for search:" << endl; cin >> d; unsigned pos=ol.find( d ); if( pos==(unsigned)-1 ) cout << "not found!" << endl; else cout << "found at " << pos << endl; DATA nd; for( int i=0; i<3; i++ ){ cout << "input old data and new data:\n"; cin >> d >> nd; ol.update( d, nd ); cout << ol << endl; } for( int i=0; i<3; i++ ){ cout << "input a data to remove:" << endl; cin >> d; ol.erase( d ); cout << ol.size() << ol << endl; } cout << "is empty?" << ol.empty() << endl; ol.clear(); cout << "is empty?" << ol.empty() << endl; cout << ol.size() << ol << endl; return 0; }