链表的链式表示和实现(C++模板类实现)

 - by Hector

[CODE=cplusplus]
// 名 称 (Unit Name) : 链表List.h 头文件
// 支 持 (Support) : http://www.ourys.com
#ifndef _LIST_H
#define _LIST_H
template
class List;
/*———— 用友元类做节点 ————–*/
template
class ListNode{
public:
ListNode():next(NULL){} //用构造函数初始化指针
friend class List;
private:
DataType data;
ListNode* next;
};
/*———— 链表的定义 ————–*/
template
class List{
public:
List(); //构造带头节点的链表
~List(); //销毁线性表
void ClearList(); //将表重置为空表
bool ListEmpty(); //若为空表存在返回True
int ListLength(); //返回表中数据元素个数
bool GetElem(int i,DataType &e);//用e返回表中第i个元素的值
bool ListInsert(int i,DataType e);//在第i个元素后插入值e
bool ListDelete(int i,DataType &e);//删除第i个元素的值并返回
private:
ListNode* head; //头节点
int len; //链表长度
};
/*———— 构造带头节点的链表 ————–*/
template
List::List()
{
if(!(head=(ListNode*)malloc(sizeof(ListNode)))) exit(1);
len=0;
}
/*———— 销毁链表 ————–*/
template
List::~List()
{
DataType e;
while(len!=0) ListDelete(1,e);
free(head);
head=NULL;
}
/*———— 销毁链表 ————–*/
template
bool List::ListEmpty()
{
return len==0? true:false;
}
/*———— 返回表中数据元素个数 ————–*/
template
int List::ListLength()
{
return len;
}
/*———— 用e返回表中第i个元素的值 ————–*/
template
bool List::GetElem(int i, DataType &e)
{
if(i<1||i>len||len==0) return false;
else{
ListNode* p=head;
for(i;i>0;i–) p=p->next;
e=p->data;
return true;
}
}
/*———— 在第i个元素后插入值e ————–*/
template
bool List::ListInsert(int i,DataType e)
{
if(i<0||i>len) return false;
else{
ListNode* p;
if(!(p=(ListNode*)malloc(sizeof(ListNode)))) exit(1);
p->data=e;
if(i==0) {p->next=head->next;head->next=p;}
else{
ListNode* temp=head;
for(i;i>0;i–) temp=temp->next;
p->next=temp->next;
temp->next=p;
}
len++;
return true;
}

}
/*———— 删除第i个元素的值并返回 ————–*/
template
bool List::ListDelete(int i,DataType &e)
{
if(i<0||i>len) return false;
else{
ListNode* p=head;
ListNode* temp;
for(i;i>1;i–) p=p->next;
temp=p->next;
e=temp->data;
p->next=p->next->next;
free(temp);
temp=NULL;
len–;
return true;
}
}
#endif

/*—————- 基本测试文件 http://ourys.com原创,做人要厚道,转帖请标明来处 ——- Author:Hector ——-*/

#include
#include “List.h”
using namespace std;
int main()
{
List my;
int i,temp;
for(i=0;i<10;i++) my.ListInsert(0,i);
for(i=0;i {
my.GetElem(1+i,temp);
cout< }
for(i=10;i>0;i–)
{
my.ListDelete(i,temp);
cout< }
return 0;
}
[/CODE]

Leave a comment