C++中的链表类的设计
mylist.h //头文件 struct node { int idata_item; struct node *pnode;} //结点的定义 class mylist { private: //成员变量的说明 struct node* _at_front; struct node* _at_end; //定义该变量是为了链表的连结 int _size; public: struct node* get_front(){return _at_front;} struct node* get_end(){return _at_end;} int size(void){return _size;} void insert_front(int) void insert_end(int) bool insert(struct node*,int) int remove(int) void remove_front(void) void remove_end(void) struct node* find(int) void display(void) void reverse(void) bool equality(mylist&) mylist& concat(mylist&) mylist():_at_front(0),_at_end(0),_size(0) //构造函数 ~mylist() } 链表的实现如下: mylist.cpp //链表实现文件名 //insert实现代码 bool mylist::insert(struct node* pnode,int a) {assert(pnode!=0); struct node* temp=new struct node; if(!temp) {temp->idata_item=a; temp->pnext=pnode->pnext; pnode->pnext=temp;} return true; else cerr<<"non memory allocate"<<endl; return false;} //display实现代码 void mylist::display(void) {if(_size==0) cout<<"mylist is empty"<<endl; else { struct node *iter=_at_front; for(int i=1;i<=_size;i++) { cout<<iter->idata_item<<" "; iter=iter->pnext;} } } //reverse实现代码 void mylist::reverse(void) {struct node *temp; temp=_at_front; _at_front=_at_end; _at_end=temp; while( } //remove实现代码 int mylist::remove(int a) { struct node *iter1=_at_front; struct node *iter2=0; for(int i=1;i<=_size;i++) { if(iter1->idata_item!=a) iter2=iter1; iter1=iter1->pnext; else iter2=iter1->pnext; delete iter1; _size--; return 1; } return 0;} //insert_end实现代码 void mylist::insert_end(int a) { struct node* temp=new struct node; temp->idata_item=a; if(!_at_end) { _at_front=_at_end=temp; _size++; } else {_at_end->pnext=temp; _at_end=temp; _size++; } } //insert_front实现代码 void mylist::insert_front(int a) {struct node* temp=new struct node; temp->idata_item=a; if(!_at_front) {_at_front=_at_end=temp; _size++; } else {temp->pnext=_at_front; _at_front=temp; _size++;} }
链表是数据结构的知识,现在我们用C++的类来实现封装.
对链表类分析如下.
链表类的成员变量(private)
struct node *_at_front;
struct node *_at_end;
int _size;
链表中结点,所以定义结点如下:
struct node
{ int idata_item;
struct node *pnext;}
链表所支持的操作:
insert 插入一个结点到指定的结点后;
remove 移去一个结点;
find 查找一个结点;
reverse 翻转一个链表;
size 得到链表中结点的个数;
display 链表的输出;
equality 链表相等的判断;
concat 两个链表连结在一起;
以上是链表类的有关操作,另外加上构造函数和析构函数;
链表的声明如下: