双向循环链表的每一个结点都保存两个指针,一个指向前驱,一个指向后继,此次演示其插入,删除,建立等
//双向循环链表的实现,在插入与删除操作与单链表不同
//而涉及单方向指针操作时与单向链表差不多
#include <iostream>
#include <cstdlib>
using namespace std;
template<typename T>
struct Node{ //结点
T data;
Node<T> *next;
Node<T> *prior;
};
template<typename T>
class BcirList{
private:
Node<T> *head = NULL; //尾指针
public:
BcirList(); //创建空循环链表(带头结点)
~BcirList(); //完成摧毁操作
void CreateBcirList(int n); //创建表长为n的循环链表
void Insert(int i, T e); //在i位置插入值e
T Delete(int i); //删除i位置的值并返回它
void Clear(); //清空链表(保存头结点)
void BcirListTraverse(); //遍历表中的元素
};
//创建空循环链表(带头结点)
template<typename T>
BcirList<T>::BcirList()
{
head = new Node<T>;
if (!head)
cout << "分配内存失败 \n";
head->next = head;
head->prior = head;
}
//创建表长为n的循环链表
template<typename T>
void BcirList<T>::CreateBcirList(int n)
{
cout << "请输入数据:";
//s指向临时生存的数据,p指向当前尾元素,t一直指向头结点
Node<T> *p = head, *s = NULL, *t = head;
for (int i = 0; i < n; ++i)
{
s = new Node<T>;
cin >> s->data;
p->next = s;
s->prior = p;
t->prior = s;
s->next = t;
p = s; //p指针往下移动
}
}
//在i位置插入值e
template<typename T>
void BcirList<T>::Insert(int i, T e)
{
Node<T> *p = head->next, *s = NULL;
int j = 1;
while (p != head && j < i)
{
j++;
p = p->next; //定位到待插入结点的位置
}
if (p == head || j > i)
throw "插入位置错误 \n";
s = new Node<T>;
if (!s)
throw "内存分配失败 \n";
s->data = e;
s->prior = p->prior;
s->next = p;
p->prior->next = s;
p->prior = s;
}
//删除i位置的值并返回它
template<typename T>
T BcirList<T>::Delete(int i)
{
Node<T> *p = head->next, *s = NULL;
int j = 1, e = 0;
while (p != head && j < i)
{
j++;
p = p->next; //正好定位到要删除的结点
}
if (p == head || j > i)
throw "插入位置错误 \n";
s = p; //保存要释放的结点
e = p->data;
p->next->prior = p->prior;
p->prior->next = p->next;
delete s; //释放要删除结点的内存
return e;
}
//遍历表中的元素
template<typename T>
void BcirList<T>::BcirListTraverse()
{
Node<T> *p = head->next;
while (p != head)
{
cout << p->data << " ";
p = p->next;
}
cout << endl;
}
//清空链表(保存头结点)
template<typename T>
void BcirList<T>::Clear()
{
Node<T> *p = head->next, *s = NULL;
while (p != head)
{
s = p;
p = p->next;
delete s;
}
p->next = head;
p->prior = head;
}
//完成摧毁操作
template<typename T>
BcirList<T>::~BcirList()
{
Node<T> *p = head->next, *s = NULL;
while (p != head)
{
s = p;
p = p->next;
delete s;
}
delete head;
}
int main()
{
BcirList<int> b1;
int i = 0, j = 0;
cout << "请输入你需要的链表表实际长度:";
cin >> i;
b1.CreateBcirList(i);
cout << "表中元素为:";
b1.BcirListTraverse();
cout << "请输入你要插入的位置和值:";
cin >> i >> j;
b1.Insert(i, j);
cout << "表中元素为:";
b1.BcirListTraverse();
cout << "请输入你要删除的位置:";
cin >> i;
cout << "删除的值为:" << b1.Delete(i) << endl;
cout << "表中元素为:";
b1.BcirListTraverse();
system("pause");
return 0;
}