[转载]C++单链表操作的一个模板类 Virus

C++单链表操作

#ifndef __LINKEDLIST_HPP__
#define __LINKEDLIST_HPP__

#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000

extern C {
int exit(int);
};

//单链表结点类定义
template <class T> //结点数据域data的类型以参数 (模板)形式提供
class Node {
public: //公有成员
T data; //数据域,允许外部直接访问
private: //私有成员
Node<T> *next; //指针域(链域),指向后继结点的指针
public: //公有成员
//构造函数(初始化data和next)
Node(const T& item, Node<T> *pNext=NULL) :
data(item), next(pNext){}
//在当前结点之后插入指针p所指结点
void InsertAfter(Node<T> *p) {
if (!p) return; //若p为空,则返回
p->next = next; //将待插入结点p的next指向当前结点的next域
next = p; //将当前结点的next更新为待插入结点p
}
//删除当前结点的后继结点并返回被删除结点的地址
Node<T> *DeleteAfter() {
if (!next) return NULL; //若无后继(next为NULL),则返回
Node<T> *pNext = next; //next不为空,则记录其地址(留待函数返回后做处理)
next = next->next; //用后继结点(next)的后继来更改当前结点的next域
return pNext; //返回已记录下的待删除结点地址
}
//返回指向当前结点的后继结点的指针
Node<T> *NextNode() const { return next; }
T GetData() const { return data; }
void SetData(const T &item) { data = item; }
};
//单链表类定义
template <class T>
class LinkedList {
private:
Node<T> *front, *rear; //表头,表尾
Node<T> *currptr; //指向当前结点的指针
int size; //表长(结点的个数)
private:
//生成新结点
Node<T> *GetNode(const T& item, Node<T> *pNext = NULL) {
Node<T> *newNode;
//新分配一结点存储空间并初始化数据成员
newNode = new Node<T>(item, pNext);
if (!newNode) {
cerr << 存储空间分配失败!程序将终止。 << endl;
exit(1);
}
return newNode;
}
//释放结点p
void *freeNode(Node<T> *p) { if (p) delete p; }
private:
//当链表为空时插入结点时的处理
int InsertNewNodeWhenListIsEmpty(const T &item) {
if (size > 0) return 0; //不为空表,返回False(0)
currptr = GetNode(item);
front = currptr;
rear = currptr;
size ++;
return 1; //在空表中插入了结点,返回True(1)
}
public:
//构造函数
LinkedList() {
front = NULL;
rear = NULL;
currptr = NULL;
size = 0;
}

【Blog】http://virusswb.cnblogs.com/

【MSN】jorden008@hotmail.com

【说明】转载请标明出处,谢谢

反馈文章质量,你可以通过快速通道评论:

原文地址:https://www.cnblogs.com/virusswb/p/837694.html