什么是双向循环链表
1、拥有两个指针域prior以及next
,一个数据域data
2、尾部的next
指针 指向头结点
存储结构
typedef struct DuLNode {
ElemType data;
struct DuLNode *prior;
struct DuLNode *next;
}DuLNode,*DuLinklist;
带头结点双链循环表创建
1、创建头结点
2、在循环中创建新结点
3、使用一个变量记住头结点
4、然后使用这个变量来进行更替
void CreateDuList(DuLinklist &DL, int num) {
传入链表以及要创建的链表个数
//带头节点创建
DL = (DuLinklist)malloc(sizeof(DuLNode));
DL->next = NULL;
DL->prior = NULL;
printf("开始初始化数据:\n");
DuLinklist P;
P = DL;
for (int i = 0; i < num; i++) {
//开始创建新的结点
DuLinklist L= (DuLinklist)malloc(sizeof(DuLNode));
printf("请输入第%d个数据:", i + 1);
printf("\n");
scanf("%d", &L->data);
L->prior = P;
P->next = L;
L->next = DL;
DL->prior = L;
P = L;
}
}
双向循环表插入
1、创建需要插入的结点
2、找到待插入的位置的结点
3、更换该结点的指针域
void InsertDul(DuLinklist &DL, int Location, int num)
{
传入位置和要插入的值
//首先创建一个结点存储data
DuLinklist New_data = (DuLinklist)malloc(sizeof(DuLNode));
New_data->data = num;
New_data->prior = NULL;
New_data->next = NULL;
DuLinklist s = GetElem(DL, Location);
New_data->prior = s->prior;
New_data->next = s;
s->prior->next = New_data;
s->prior = New_data;
}
双向循环链表查找
1、定义新变量,用来接收该位置的原结点
2、定义变量,作为指针滑动的工具
3、Location+1
是因为:这是带头结点的双向链表,但是头结点不存储数据。
所以不论是查找还是访问结点数据。都是从头结点的下一个开始
DuLinklist GetElem(DuLinklist DL, int Location) {
传入要插入的位置
DuLinklist p = DL;
DuLinklist s = DL;
int i = 0;
while (p)
{
s = p;
p = p->next;
i++;
if (i == Location+1)
break;
else
continue;
}
printf("当前位置(%d)的值为:%d\n", Location,s->data);
return s;
}
双向循环表的删除
1、首先找到需要删除的结点
2、更改其指针域即可
3、最后释放该被删除的结点
void DeleteData(DuLinklist &DL, int Location, int &elem) {
传入删除的位置
使用elem返回删除结点的值
DuLinklist L = GetElem(DL, Location);
elem = L->data;
L->next->prior = L->prior;
L->prior->next = L->next;
free(L);
}
在删除代码中我遇到的问题,错误代码如下:
L->prior = L->next->prior ;
L->prior->next = L->next;
这段错误代码,导致最后在访问数据时出现了错误。于是我重新画图演示指针的指向。
我们本应该修改L->next->prior
,让后面结点的prior
指向L
前面的结点
但是我在这里写反了
L->prior = L->next->prior;
这串代码意思是:把(L后面结点的prior内的地址)L自己的地址给自己的prior域
中。这很明显的有逻辑错误。
还好最后修正,及时反应过来了