文档详情

c++链表类模板的实现(清华大学出版社 C++语言程序设计第4版)(课本).doc

发布:2017-08-20约8.11千字共14页下载文档
文本预览下载声明
c++链表类模板的实现(清华大学出版社 C++语言程序设计第4版)(课本) //node.h #ifndef NODE_H//结点类模板 #define NODE_H templateclass T class linkedlist;//新添 templateclass T//新添 class node { private: nodeT*next;//指向后继指针的结点 public: T data;//数据域 node(const Tdata,nodeT*next=0);//构造函数 void insertAfter(nodeT*p);//在本结点之后插入一个同类的结点P nodeT*deleteAfter();//删除本结点的后继结点,并返回其地址 nodeT*nextNode();//获取后继结点的地址 const nodeT*nextNode()const;//获取后继结点的地址 friend linkedlistT;//因操作需要将linkedlistT作为node的友元(新添) }; templateclass T nodeT::node(const Tdata,nodeT*next/*=0*/):data(data),next(next) { } templateclass T nodeT*nodeT::nextNode() { return next; } templateclass T const nodeT*nodeT::nextNode()const { return next; } templateclass T void nodeT::insertAfter(nodeT*p) { p-next=next; next=p; } templateclass T nodeT*nodeT::deleteAfter() { nodeT*tempPtr=next; if(next==0)return 0; next=tempPtr-next; return tempPtr; } #endif //linkedlist.h #ifndef LINKEDLIST_H #define LINKEDLIST_H #includeiostream #include node.h templateclass T class linkedlist { private: nodeT*front,*rear;//表头和表尾指针 nodeT*prevPtr,*currPtr;//记录表当前遍历位置的指针,由插入和删除操作更新 int size;//表中的元素个数 int position;//当前元素在表中的位置序号,由函数reset使用 //函数成员: //生成新结点,数据域为item,指针域为ptrNext nodeT*nextNode(const Titem,nodeT*ptrNext=NULL); void freeNode(nodeT*p);//释放结点 (未用) //将链表L复制到当前表(假设当前表为空) //被复制构造函数和“operator=”调用 void copy(linkedlistTL);//(因实现需要,无法使用(linkedlistTconstL)作为形参表) public: void print();//打印链表类里的数据及其数目(新添) linkedlist(); linkedlist(linkedlistTL);//复制构造函数(因实现需要,无法使用(linkedlistTconstL)作为形参表) ~linkedlist(); linkedlistToperator=(linkedlistTL);//重载赋值运算符(因实现需要,无法使用(linkedlistTconstL)作为形参表) int getSize()const;//返回链表中的元素个数 bool isEmpty()const;//链表是否为空 (未用) void reset(int pos=0);//初始化游标的位置(第一位数的位置设为0) void next();//使游标移动到下一个结点 bool endOfList()const;//游标是否到了链尾 int currentPosition(void);//返回游标当前的位置 void insertFront(const Titem);//在表头插入结点 void ins
显示全部
相似文档