1.首先回忆一下之前链表的创建方式
尾插法创建链表
Node *CreateLinkListByTail(int n){
Node *p;
//初始化链表的头结点
LinkList=new Node;
//指针域为空
linkList->next=NULL;
head=LinkList;
for(auto i=0;i<n;i++){
p=new Node;
p->data=i;
LinkList->next=p;
LinkList=p;
}
LinkList->next=NULL;
return head;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
2.尾插法创建循环链表算法
Node *CreateLoopLinkList(int n){
Node *p;
Node *tail;//指向尾结点的指针
LinkList=new Node;
LinkList->next=NULL;
head=LinkList;
for(auto i=0;i<n;i++){
p=new Node;
p->data=i;
LinkList->next=p;
LinkList=p;
}
//将尾结点赋值给尾指针
tail=LinkList;
//将尾指针的指针域指向头结点指向的指针域
tail->next=head->next;
return head;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
遍历链表
//遍历链表
void ForeachLinkList(Node *tail, bool isLoopLinkList = false)
{
if (isLoopLinkList)
{
Node *p = tail->next;
while (p->next != head->next)
{
cout << p->data << endl;
p = p->next;
}
return;
}
// 循环链表的遍历方式,循环输出链表的元素,用于检测循环链表是否创建成功
while (head->next)
{
std::cout << head->next->data << " ";
head = head->next;
}
}