#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; inext )
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;
}
|
|
|
| 日 | 一 | 二 | 三 | 四 | 五 | 六 |
---|
24 | 25 | 26 | 27 | 28 | 29 | 30 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 1 | 2 | 3 | 4 |
|
导航
统计
常用链接
留言簿(1)
随笔档案
搜索
最新评论
阅读排行榜
评论排行榜
|
|