双向循环链表
插入操作
s->next = p;
s->prior = p->prior;
p->prior->next = s;
p->prior = s;
删除操作
p->prior ->next= p->next;
p->next ->prior = p->priof;
free(p); //释放内存空间
总结:双向链表可以有效提高算法的时间性能,用空间换取时间
案例
程序
#include <iostream>
using namespace std;
typedef char ElemType;
typedef struct DualNode
{
ElemType data;
struct DualNode* prior;
struct DualNode* next;
}DualNode , *DualLinkList;
//建立双向循环链表
bool creatDualList(DualLinkList *l)
{
const char* a = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
DualNode* p, * q;
*l = (DualNode*)malloc(sizeof(DualNode));
if (!(*l))
return false;
(*l)->next = (*l)->prior = nullptr;
p = (*l);
for (int i = 0; i < 26; i++)
{
q = (DualNode*)malloc(sizeof(DualNode));
if (!q)
{
return false;
}
q->data = a[i];
q->prior = p;
q->next = p->next;
p->next = q;
p = q;
}
p->next = (*l)->next;
(*l)->next->prior = p;
(*l) = p->next; //将开始结点*l 固定在'A' 处
return true;
}
void SetLinkList(DualLinkList *l,int i)
{
if (i>0)
{
//do while 和while 两种循环结构
do
{
(*l) = (*l)->next;
} while (--i);
/*while (i)
{
(*l) = (*l)->next;
i--;
}*/
}
if (i < 0)
{
do
{
(*l) = (*l)->prior;
} while (++i);
/*while (i)
{
(*l) = (*l)->prior;
i++;
}*/
}
}
int main()
{
int n;
DualLinkList l;
while (true)
{
creatDualList(&l);
cout << "请输入一个整数:";
cin >> n;
SetLinkList(&l, n);
for (int i = 0; i < 26; i++)
{
cout << l->data;
l = l->next;
}
cout << endl;
}
system("pause");
return 0;
}