——————————————————————————————————————————————————————————————————
一、实验目的
1、掌握线性表的基本操作:插入、删除、查找。
2、掌握链表遍历器的使用方法。
二、实验内容
1、创建线性表类。线性表的存储结构使用链表。
2、提供操作:自表首插入元素、删除指定元素、搜索表中是否有指定元素、输出链表。
3、接收键盘录入的一系列整数(例10,25,8,33,60)作为节点的元素值,创建链表。输出链表内容。
4、输入一个整数(例33),在链表中进行搜索,输出其在链表中的位置。如果不存在输出0。
5、使用链表遍历器实现链表的反序输出。
6、创建两个有序链表,使用链表遍历器实现链表的合并。
——————————————————————————————————————————————————————————————————
下面是我的代码: 点此下载链表源代码
——————————————————————————————————————————————————————————————————
template<class T> class ChainNode{ public: T data; ChainNode<T> *link; }; template<class T> class Chain{ public: Chain(){first=0;} ~Chain(); Chain<T>& Insert(const T& x); Chain<T>& Delete(int k,T& x); int Search(const T& x) const; void Output(ostream& out) const; ChainNode<T> *first; };Chain是一个链表,里面的节点是ChainNode
template<class T> Chain<T>::~ Chain( ) { // 链表的析构函数,用于删除链表中的所有节点 ChainNode<T> *next; // 下一个节点 while (first) { next = first->link; delete first; first = next; } } template<class T> Chain<T>& Chain<T>::Insert(const T& x) { // 作为第一个元素插入 ChainNode<T> *y=new ChainNode<T>; y->data = x; y->link = first; first = y; return *this; } template<class T> Chain<T>& Chain<T>::Delete(int k, T& x) { // 把第k个元素取至x,然后从链表中删除第k个元素 // p最终将指向第k个节点 ChainNode<T> *p = first; // 将p移动至第k个元素,并从链表中删除该元素 if (k == 1) // p已经指向第k个元素 //2.删除首结点 first = first->link; // 删除之 else { // 用q指向第k - 1个元素 //3.删除其它结点 ChainNode<T> *q = first; for (int index = 1; index < k - 1 && q; index++) q = q->link; p = q->link; // 存在第k个元素 q->link = p->link; } // 从链表中删除该元素 //保存第k个元素并释放节点p x = p->data; delete p; return *this;} template<class T> int Chain<T>::Search(const T& x) const { // 寻找x,如果发现x,则返回x的地址 //如果x不在链表中,则返回0 ChainNode<T> *current = first; int index = 1; while (current && current->data != x) { current = current->link; index++ ; } if (current) return index; return 0; } template<class T> void Chain<T>::Output(ostream& out) const { // 将链表元素送至输出流 ChainNode<T> *current; for (current=first; current; current=current->link) out << current->data << " "; } //重载操作符< < template <class T> ostream& operator<<(ostream& out, const Chain<T>& x) { x.Output(out); return out; }
//链表遍历器 template<class T> class ChainIterator { public : T* Initialize(const Chain<T>& c) { location = c.first; if (location) return &location->data; return 0; } T* Next() { if (!location) return 0; location = location->link; if (location) return &location->data; return 0; } private: ChainNode<T> *location; //节点位置指针 };用来访问链表的类,在测试链表类的时候使用方便访问链表中的数据。