#include<iostream>
using namespace std;
class Chain;
class Node
{
friend class Chain;
private:
char data;
Node *next;
};
class Chain
{
public:
Chain();
~Chain();
void ClearList();//将表清空
bool Find(int i , char &x); //将下标为i的元素取至x中
int Search(const char &x);//返回x在表中的下标
bool Insert(int i, const char &x);//在下标为i的结点前插入x
bool Delete(int i ,char &x);//将下标为i的结点的值存入x,并删除i
void Output();//输出表中所有元素
private:
Node *head; //头指针
int length; //表长
};
Chain::Chain() //构造函数
{
head = new Node; //为头指针申请头结点,也即head指向的是头结点
//头结点不是第一个结点,
head->next = 0; //头结点不指向任何地方
length = 0;
}
Chain::~Chain() //析构函数
{
ClearList();
delete head;
}
bool Chain::Find(int i , char &x) //将下标为i的元素取至x中
{
if(i<0 || i>length -1) return false;
Node *p = head->next;
int k = 0;
while(k<i) //将p指向第i个元素
{
p = p->next;
k++;
}
x = p->data;
return true;
}
int Chain::Search(const char &x) //找到与元素x相等的元素并返回下标
{
Node *p = head->next;
int i = 0;
while(p != 0)
{
if(p->data == x) return i;
p = p->next;
i++;
}
return -1;
}
bool Chain::Insert(int i, const char &x) //将x插入第i个元素前面
{
if(i < 0 || i > length) return false;
Node *p = head;
int k = 0;
while(k <= i-1){p = p->next; k++;}
Node *q;
q = new Node;
q->data = x;
q->next = p->next;
p->next = q;
length++;
return true;
}
bool Chain::Delete(int i ,char &x)//将下标为i的结点的值存入x,并删除i
{
if(i < 0 || i > length) return false;
Node *p = head;
for(int k =0; k<i; k++) p = p->next;//找到第i个结点的前一个结点p
Node *q = p->next;//第i个结点为q
x = q->data;
p->next = q->next;
delete q;
length--;
return true;
}
void Chain::ClearList()
{
Node *p = head->next, *q;
while(p != 0) //p在前,q在后,删除p后第二次循环又是p在前,q在后
{
q = p;
p = p->next;
delete q;
}
head->next = 0;
length = 0;
}
void Chain::Output()
{
Node *p = head->next;
while(p != 0)
{
cout<<p->data;
p = p->next;
}
}
void main()
{
char str[] = "ABCDEFG";
Chain L;
for(int i = 0; str[i] != '\0';i++)
{
L.Insert(i,str[i]);
}
L.Output();
cout<<endl;
system("pause");
}