#include <iostream>
struct Lnode
{
char data;
Lnode *next;
};
Lnode* Creat_Circle_Lnode(int n){
if (n < 3)
{
throw "little than 3";
}
// head pointer
Lnode *head = new Lnode;
// head lnode
Lnode *head_lnode = new Lnode;
Lnode *r = new Lnode;
head_lnode = r;
for (int i = 0; i < n; i++)
{
Lnode *p = new Lnode;
std::cout<<"Input marks to this Lnode:";
p->data = getchar();
while (std::cin.get() != '\n');
r->next = p;
r = p;
}
Lnode *l = new Lnode;
l = head_lnode;
for (int i = 0; i < n - 3; i++)
{
l = l->next;
}
r->next = l;
head->next = head_lnode;
head_lnode =NULL;
l = nullptr;
r = nullptr;
return head;
}
void test(){
Lnode *p = new Lnode;
try
{
p = Creat_Circle_Lnode(5);
}
catch(const std::exception& e)
{
std::cerr << e.what() << '\n';
}
// Judege if has circle
// to creat the fast_pointer and low_pointers
Lnode *fast_pointer = new Lnode;
Lnode *low_pointer = new Lnode;
fast_pointer = low_pointer = p;
while (fast_pointer->next != NULL && fast_pointer->next->next != nullptr)
{
low_pointer = low_pointer->next;
fast_pointer = fast_pointer->next->next;
if (fast_pointer == low_pointer)
{
std::cout<<"链表有环"<<std::endl;
break;
}
}
low_pointer = p;
while (low_pointer != fast_pointer)
{
low_pointer = low_pointer->next;
fast_pointer = fast_pointer->next;
}
std::cout<<"The mark of enterance: "<<fast_pointer->data<<std::endl;
}
int main(void){
test();
return 0;
}
C++ 代码实现【环形链表】 判断链表是否有环以及寻找环的起点
最新推荐文章于 2025-03-06 16:36:53 发布