判断一个单链表中是否有环

// 判断一个单链表中是否有环.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <iostream>

//定义单链表的长度
const int length = 22;
//定义单链表中环的起点
const int circularNum = 11;

struct Node
{
     int value;
     struct Node *next;
 };
 
Node *createCircularLinklist(int num)
{ 
     Node *head, *last, *p, *temp;
     head = (Node *)malloc(sizeof(Node));
     last = (Node *)malloc(sizeof(Node));
 
     for(int i=0; i<length; i++)
	 {
         p = (Node *)malloc(sizeof(Node));
         p->value = i;
         p->next = NULL;
         if(i == 0) 
             head->next = p;

         if(i == num) 
             temp = p;

         last->next = p;
         last = p;
     }
 
     last->next = temp; //最后一个点指向环的起点
 
     return head->next;
}

void traverse(Node *ptr)
{
     int count = 0;
     while(ptr != NULL)
	 {
         if(count>length)
			 break;
         std::cout << ptr->value;
         if(ptr->next != NULL) 
			 std::cout << " -> ";
         ptr = ptr->next;
         count++;
     }
     std::cout<<std::endl;
}

int isCircular(Node *list)
{
     bool isLoop = false;
     if(list == NULL) return -1;
     Node *ptr_fast,*ptr_slow;
     ptr_fast = list;
     ptr_slow = list;
 
     while(ptr_fast->next && ptr_fast->next->next)
	 {
         ptr_fast = ptr_fast->next->next;
         ptr_slow = ptr_slow->next;
 
         if(ptr_fast == ptr_slow){
             isLoop = true;
             std::cout<<"It's Circular!"<<" Meeting at: "<<ptr_fast->value<<std::endl;
             break;
         }
     }
 
     if(!isLoop){
         std::cout<<"It's not Circular!"<<std::endl;
         return -1;
     }
 
     int length = 0;
     while(ptr_fast->next && ptr_fast->next->next){
         ptr_fast = ptr_fast->next->next;
         ptr_slow = ptr_slow->next;
         length++;
         if(ptr_fast==ptr_slow){
             std::cout<<"The length: "<<length<<" Meeting at: "<<ptr_fast->value<<std::endl;
             break;
         }
     }

     ptr_fast = list;
     int len = 0;
     while(ptr_fast!=ptr_slow){
         ptr_fast = ptr_fast->next;
         ptr_slow = ptr_slow->next;
         len++;
     }
     std::cout<<"Starting node: "<<ptr_fast->value<<std::endl;
     std::cout<<"lenght of link: "<<len+length<<std::endl;
}
 
int main()
{
     Node *list = createCircularLinklist(circularNum);
     traverse(list);
     isCircular(list);
     return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值