原书这部分内容很多,至少相对于循环链表是很多。相信当你把单链表的指针域搞清楚后,这部分应该难不倒你。现在我的问题是,能不能从单链表派生出双向链表?<?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" />
你可以有几种做法:
一种就是先定义一个双链节点--但是,它的名字必须叫node,这是没办法的事;不然你就只好拷贝一份单链表的实现文件,把其中的node全都替换成你的双链节点名字,但是这就不叫继承了。
另一种做法就是先定义一种结构例如这样的:
| template <class type> class newtype { public: type data; node<newtype> *link; } |
| protected: void put(node<type> *p)//尽量不用,双向链表将使用这个完成向前移动 { current = p; } void putprior(node<type> *p)//尽量不用,原因同上 { prior = p; } |
| #ifndef dbllist_h #define dbllist_h #include "list.h" template <class type> class dbllist : public list< node<type> > { public: type *get() { if (pget() != null) return &pget()->data.data; else return null; } type *next() { pnext(); return get(); } type *prior() { if (pgetprior != null) { put(pgetprior()); putprior( (node< node<type> >*)pget()->data.link); return get(); } return null; } void insert(const type &value) { node<type> newdata(value, (node<type>*)pget()); list< node<type> >::insert(newdata); if (pgetnext()->link != null) pgetnext()->link->data.link = (node<type>*)pgetnext(); } bool remove() { if (list< node<type> >::remove()) { pget()->data.link = (node<type>*)pgetprior(); return ture; } return false; } }; #endif |
| void dbllisttest_int() { dbllist<int> a; for (int i = 10; i > 1; i--) a.insert(i); for (i = 10; i > 1; i--) cout << *a.next() << " "; a.first(); cout << endl; cout << *a.next() << endl; cout << *a.next() << endl; cout << *a.next() << endl; cout << *a.next() << endl; a.remove(); cout << *a.get() << endl; cout << *a.prior() << endl; cout << *a.prior() << endl; cout << *a.prior() << endl; } |
Java Asp PHP .Net XML C/C++ CGI VB Jsp J2ee J2se J2me EJB Servlet Tomcat Resin Struts Weblogic Eclipse ANT GUI JMS Web servise IDEA Webphere Hibernate Spring Jboss Applet Swing Socket Javamail Perl Ajax P2P 安全 模式 框架 测试 开源 游戏
Windows XP Windows 2000 Windows 2003 Windows Me Windows 9.x Linux UNIX 注册表 操作系统 服务器 应用服务器