谈谈这样设计链表的优缺点?你们一般怎样设计?
- C/C++ code
#ifndef COORDINATELIST#define COORDINATELIST class CoordinateList/****************许多人在设计链表时常常在其外再包裹一层结构体,这里,我将链表的元素个数存储在头节点的ID变量中,充分利用了链表所申请的内存,然而,在每次定位链表中的节点时,需要从头节点遍历到目标节点,这似乎会影响效率,但在这里,我不打算在数据源中增加一个存放当前节点地址的变量,考虑到这样虽然减少了计算量,但增加了内存开销*****************************************************************************/{private: int x; int y; int ID; //坐标标识,但对于头节点而言,ID为坐标表中的元素个数protected: CoordinateList *next;public: CoordinateList(); void Add(int x,int y); int GetX(int ID); int GetY(int ID); int GetSize();};#endif#include"StdAfx.h"#include"CMyCoordinateList.h"#define NULL 0//#include<afx.h> 是否应该包含这个文件?CoordinateList::CoordinateList(){ this->next=NULL; this->ID=0;}int CoordinateList::GetSize(){ return this->ID;}void CoordinateList::Add(int x,int y){ CoordinateList *p,*q; int i=0; p=this; while(p->next!=NULL) { p=p->next; i++; } q=new(CoordinateList); q->x=x; q->y=y; q->ID=i; q->next=p->next; p->next=q; this->ID++; //表的节点数变大 }int CoordinateList::GetX(int ID){ CoordinateList *p; p=this; while(p->next!=NULL) { p=p->next; if(p->ID==ID) return p->x; } return -1; //不存在所要找的ID}int CoordinateList::GetY(int ID){ CoordinateList *p; p=this; while(p->next!=NULL) { p=p->next; if(p->ID==ID) return p->y; } return -1; }[解决办法]
既然这种单向链表,就不是为了实现查询的。
要查询就实现map或者table
[解决办法]
你既然觉得增加内存开销,那你就把ID 和add()定义为static ,这两个属性和行为 本来就是你的类共有的,
- C/C++ code
int CoordinateList::GetY(int ID){ CoordinateList *p; int i=0; p=this; while(p->next!=NULL) { p=p->next; if(i++==ID) return p->y; } return -1; }
[解决办法]
[解决办法]
既然你这么写说明你节点数不多,既然节点数不多其实你还不如直接用数组
[解决办法]
[解决办法]