【王道数据结构】【chapter2线性表】【P43t15】

文章介绍了如何使用C++编写一个算法,通过定义快慢指针来判断单链表是否存在环。在示例代码中,首先初始化链表并创建环,然后调用`is_cir`函数进行检测。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

单链表有环,是指单链表的最后一个节点的指针指向了链表中的某个结点(通常单链表的最后一个节点的指针域是空的)。试编写算法判断单链表是否存在环。

#include <iostream>

typedef  struct node{
    int data;
    node* next;
}node,*list;

list Init()
{
    list head=(list) malloc(sizeof (node));
    head->next= nullptr;
    head->data=-1;
    return head;
}

list Buynewnode(int x)
{
    list tmp=new node;
    tmp->next= nullptr;
    tmp->data=x;
    return tmp;
}

void print(list head)
{
    for(list pointer=head->next;pointer!= nullptr;pointer=pointer->next) {
        printf("%3d",pointer->data);
    }
    puts("");
}

void is_cir(list head)
{
    list slow=head,fast=head;
    while(fast)
    {
        slow=slow->next;
        fast=fast->next;
        if(fast) {
            fast=fast->next;
        }
        else break;
        if(fast==slow) {
            printf("there is a circle\n");
            return ;
        }
    }
    printf("there is no circle\n");
    return;
}
int main() {
    list head=Init();
    list pointer=head;
    list record= nullptr;
    //制造环
    for(int i=0;i<10;i++)
    {
        if(i==6) record=pointer;
        pointer=pointer->next= Buynewnode(i+1);
    }
    pointer->next=record;
    is_cir(head);

    list head2=Init();
    pointer=head2;
    record= nullptr;
    for(int i=0;i<10;i++)
    {
        pointer=pointer->next= Buynewnode(i+1);
    }
    is_cir(head2);

    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

桜キャンドル淵

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值