c++链表的基本操作(类)
基本功能列表
void InitList(); //初始化
void CreatList(Elemtype a[],int n); //创建
void DestroyList();//销毁
bool ListEmpty();//是否为空
int ListLength(); //长度
bool DisplayList();//全部输出
bool GetElem(Elemtype &e,int n); //得到某数据元素
bool DeleteElem(Elemtype &e,int n); //删除
bool InsertElem(int i,Elemtype e); //插入
这些是我目前实现的功能,通过看书和自己的理解编写的通过c++类实现的链表
下面是总代码,类名是linklist
#include <iostream>
using namespace std;
typedef int Elemtype;
typedef struct linklink
{
Elemtype data;
struct linklink *next;
}LinkNode;
class linklist
{
public:
void InitList(); //初始化
void CreatList(Elemtype a[],int n); //创建
void DestroyList();//销毁
bool ListEmpty();//是否为空
int ListLength(); //长度
bool DisplayList();//全部输出
bool GetElem(Elemtype &e,int n); //得到某数据元素
bool DeleteElem(Elemtype &e,int n); //删除
bool InsertElem(int i,Elemtype e); //插入
private:
LinkNode*head;
};
void linklist::InitList()
{
head = (LinkNode*)malloc(sizeof(LinkNode));
head->next = NULL;
head->data=0;
}
void linklist::CreatList(Elemtype a[],int n)
{
LinkNode*p, *r;
int i;
head->data=n;
head = (LinkNode*)malloc(sizeof(LinkNode));
r = head;
for (i = 0; i < n; i++)
{
p = (LinkNode*)malloc(sizeof(LinkNode));
p->data = a[i];
r->next = p;
r = p;
}
r->next = NULL;
}
void linklist::DestroyList()
{
LinkNode*pre=head,*p=head->next;
{
while (p != NULL)
{
free(pre);
pre = p;
p = p->next;
}
//free(pre);
}
head->next=NULL;
}
bool linklist::ListEmpty()
{
return (head->next == NULL);
}
bool linklist::DisplayList()
{
LinkNode*p = head;
if (p->next == NULL)
{
return false;
}
while (p->next != NULL)
{
p = p->next;
cout << p->data << " ";
}
cout << endl;
return true;
}
int linklist::ListLength()
{
LinkNode*p=head;
int length=0;
while (p->next != NULL)
{
p = p->next;
length++;
}
return length;
}
bool linklist::GetElem(Elemtype &e,int n)
{
LinkNode*p = head;
while (p->next != NULL)
{
p = p->next;
n--;
if (!n)
{
e = p->data;
return true;
}
}
return false;
}
bool linklist::DeleteElem(Elemtype &e,int n) //
{
n--;
if(n<0||n>head->data)
return false;
LinkNode *pre = head, *p;
while (pre->next != NULL)
{
if (!n)
{
p = pre->next;
e = p->data;
pre->next = p->next;
free(p);
return true;
}
pre = pre->next;
n--;
}
head->data--;
return false;
}
bool linklist::InsertElem(int i,Elemtype e)
{
int j;
LinkNode *p=head,*s;
if(i<=0)return false;
while(j<i-1&&p!=NULL)
{
j++;
p=p->next;
}
if(p==NULL)
{
return false;
}
else
{
s=(LinkNode*)malloc(sizeof(LinkNode));
s->data = e;
s->next=p->next;
p->next=s;
head->data++;
return true;
}
}
int main()
{
Elemtype e;
Elemtype sz[] = { 1,2,3,4,5,6,7,8,9 };
linklist L;
L.InitList();
L.CreatList(sz, 9);
L.DisplayList();
//L.GetElem(e, 1);
/*if (L.ListEmpty())
{
cout << "空";
}
else
cout << "不空";*/
//cout << L.ListLength();
//L.DeleteElem(e, 1);
L.InsertElem(1,99);
cout << endl;
L.DestroyList();
L.DisplayList();
//cout << e;
return 0;
}
主函数是随意弄的,自己试试就ok