- #include<iostream.h>
- struct element
- { //定义节点结构
- int val; //数据元素域
- element *next; //链指针域
- };
- class list
- { //list类定义
- element *elems; //elems为当前标识指针
- public:
- list(){elems=0;}
- ~list(); //析构函数
- virtual bool insert(int val); //虚函数
- virtual bool deletes(int val); //虚函数
- bool contain(int val);
- virtual void print();
- };
- class set:public list
- {
- int card;
- public:
- set(){card=0;};
- bool insert(int val);
- bool deletes(int val);
- void print();
- };
- list::~list()
- {
- element *tmp=elems;
- for(element *elem=elems;elem!=NULL;)
- { //循环释放各元素所占的内存
- tmp=elem;
- elem=elem->next;
- delete tmp;
- }
- }
- bool list::insert(int val)
- { //插入元素函数
- element *elem=new element; //分配内存
- if(elem!=NULL)
- { //将新元素插入到当前标识指针elems处
- elem->val=val;
- elem->next=elems;
- elems=elem;
- return true;
- }
- else return false;
- }
- bool list::deletes(int val)
- { //删除元素函数
- if (elems==NULL) //如链表为空返回false
- return false;
- element *tmp=elems;
- if(elems->val==val)
- {
- elems=elems->next;
- delete tmp;
- return true;
- }
- else
- for(element *elem=elems;elem->next!=NULL;elem=elem->next)
- if(elem->next->val==val)
- {
- tmp=elem->next;
- elem->next=tmp->next;
- delete tmp;
- return true;
- }
- return false;
- }
- bool list::contain(int val)
- { //判断元素val在链表中是否存在
- if(elems==NULL)
- return false;
- if (elems->val==val)
- return true;
- else
- for(element *elem=elems;elem->next!=NULL;elem=elem->next)
- if(elem->next->val==val)
- return true;
- return false;
- }
- void list::print()
- { //输出链表的各元素
- cout<<"调用基类的print()函数!"<<endl;
- cout<<"链表元素为:";
- if(elems==NULL)
- return;
- for(element *elem=elems;elem!=NULL;elem=elem->next)
- cout<<elem->val<<" ";
- cout<<endl;
- }
- bool set::insert(int val)
- {
- if(!contain(val) && list::insert(val))
- {
- ++card;
- return true;
- }
- return false;
- }
- bool set::deletes(int val)
- {
- if(list::deletes(val))
- {
- --card;
- return true;
- }
- return false;
- }
- void set::print()
- {
- cout<<"调用派生类的print()函数!"<<endl;
- cout<<"集合元素为:";
- list::print();
- cout<<"集合元素个数为:"<<card;
- cout<<endl;
- }
- void main()
- {
- list *p,list1;
- set set1;
- p=&list1;
- p->insert(12);
- p->insert(34);
- p->insert(56);
- p->insert(78);
- p->insert(90);
- p->print();
- p->deletes(56);
- p->deletes(40);
- p->print();
- cout<<endl;
- p=&set1;
- p->insert(123);
- p->insert(234);
- p->insert(345);
- p->insert(123);
- p->print();
- p->deletes(123);
- p->deletes(456);
- p->print();
- }