#include<iostream>
using namespace std;
typedef struct DNode {
int data;
struct DNode *prev;
struct DNode *next;
} DNode, *DLinkList;
// 初始化循环双链表
void InitDLinkList(DLinkList &D) {
D = new DNode;
D->prev = D; // 头结点的 prev 指向自己
D->next = D; // 头结点的 next 指向自己
}
// 遍历循环双链表
void Print_D(DLinkList &D) {
if (D == NULL || D->next == D) {
cout << "循环双链表为空" << endl;
return;
}
DLinkList p = D->next;
while (p != D) {
cout << p->data << " ";
p = p->next;
}
cout << endl;
}
// 在D中第i个元素之前插入数据元素e
int Insert_D(DLinkList &D, int i, int e) {
if (D == NULL || i < 1) {
return -1;
}
DLinkList p = D;
int j = 0;
// 找到第i-1个元素
while (p->next != D && j < i - 1) {
p = p->next;
j++;
}
if (j != i - 1) {
return -1;
}
DLinkList s = new DNode;
s->data = e;
// 先更新新结点的前驱和后继指针
s->next = p->next;
s->prev = p;
// 再更新原链表中相邻结点的前驱和后继指针
p->next->prev = s;
p->next = s;
return 1;
}
int main() {
DLinkList L;
InitDLinkList(L);
Insert_D(L, 1, 1);
Insert_D(L, 2, 2);
Insert_D(L, 3, 3);
Insert_D(L, 4, 4);
Insert_D(L, 5, 5);
cout << "循环双链表: ";
Print_D(L);
Insert_D(L, 3, 10); // 在第3个元素之前插入10
cout << "插入10后的循环双链表: ";
Print_D(L);
return 0;
}
遍历循环双链表
在遍历循环双链表时,我们需要从第一个实际数据结点开始,一直遍历到回到头结点为止。头结点本身不存储数据,所以我们不需要输出头结点的数据。
详细步骤:
-
初始化指针
p:-
DLinkList p = D->next;:将指针p指向头结点的下一个结点,即第一个实际数据结点。
-
-
循环条件
p != D:-
while (p != D):当p不等于头结点D时,继续循环。 -
这意味着当
p再次回到头结点时,循环停止。
-
-
输出数据:
-
cout << p->data << " ";:输出当前结点p的数据。
-
-
移动指针
p:-
p = p->next;:将指针p移动到下一个结点。
-
示例
假设我们有以下循环双链表:
复制
头结点 -> 1 -> 2 -> 3 -> 4 -> 5 -> 头结点
-
初始时,
p指向1。 -
第一次循环:输出
1,p指向2。 -
第二次循环:输出
2,p指向3。 -
第三次循环:输出
3,p指向4。 -
第四次循环:输出
4,p指向5。 -
第五次循环:输出
5,p指向头结点D。 -
此时,
p == D,循环停止。
2509

被折叠的 条评论
为什么被折叠?



