类的链表问题和执行过程
程序代码:
#include <iostream.h> enum {k1,k2,k3}; class data { public: data(int val):myval(val){cout << "数据结点建立\n";} ~data(){;} int compare(const data&); void show(){cout << myval << "\t";} private: int myval; }; int data::compare(const data& otherdata) { cout << "data的compare函数\n"; if(myval < otherdata.myval) return k1; if(myval > otherdata.myval) return k2; else return k3; } class node; class inode; class tnode; class hnode; class node { public: node(){cout << "node的构造函数\n";} virtual ~node(){} virtual node* insert(data *thedata)=0; virtual void show()=0; private: }; class inode:public node { public: inode(data* thedata,node *next); ~inode(){delete mynext;delete mydata;} virtual node* insert(data *thedata); virtual void show(){mydata->show();mynext->show();} private: data* mydata; node* mynext; }; inode::inode(data* thedata,node *next) { mydata=thedata; mynext=next; cout << "inode的构造函数\n"; } node* inode::insert(data *thedata) { cout << "i的insert\n"; int result=mydata->compare(*thedata); switch(result) { case k3: case k2: { inode* datanode=new inode(thedata,this); return datanode; } case k1: mynext=mynext->insert(thedata); return this; } return this; } class tnode:public node { public: tnode(){cout << "t的构造函数\n";} ~tnode(){} virtual node*insert(data* thedata); virtual void show(){} private: }; node* tnode::insert(data* thedata) { inode* datanode=new inode(thedata,this); cout << "tnode的insert\n"; return datanode; } class hnode:public node { public: hnode(); ~hnode(){delete mynext;} virtual node*insert(data* thedata); virtual void show(){mynext->show();} private: node* mynext; }; hnode::hnode() { mynext=new tnode; //因为mynext被初始化为tnode;所以mynext->insert调用的是tnode的insert虚函数. cout << "honde的构造函数\n"; } node* hnode::insert(data* thedata) { mynext=mynext->insert(thedata); cout << "hnode的insert\n"; return this; } class linklist { public: linklist(); ~linklist(){delete myhead;} void insert(data* thedata); void show(){myhead->show();} private: hnode *myhead; }; linklist::linklist() { myhead=new hnode; cout << "link的构造函数\n"; } void linklist::insert(data* pdata) { myhead->insert(pdata); cout << "link的insert\n"; } int main() { data* pdata; int val; linklist ll; for(;;) { cout << "what value?(0 to top)"; cin >>val; if(!val) break; pdata=new data(val); ll.insert(pdata); } ll.show(); return 0; }不太明白c++是怎么建立链表的,能详细讲解下执行过程吗?