Algorithm One Day One -- 判断链表是否有环(上)



Is a loop ? Question descrip as follows :

        Assume that wehave a head pointer to a link-list. Also assumethat we know the list is single-linked. Can you come up an algorithm to checkwhether this link list includes a loop by using O(n) time and O(1) space wheren is the length of the list? Furthermore, can you do so with O(n) time and onlyone register?

/********************************************************************  
created:2015年1月22日 00:54:56     
author: Jackery      
purpose: Is there a loop ?
*********************************************************************/    
#include"stdafx.h"
#include<iostream>
using namespace std;

typedef struct node
{
	int data;
	 struct node *next;
}Node,*pNode;

Node *Create(int *numNode)
{
	//创建一个链表	
	Node *head,*tail,*cnew;	
	head=NULL;	
	int num;	
	cout <<"输入数据(以#键结束):" << endl;
	while(1 )
	{
	cin >>num ;	
	if('#'==getchar())
	//以#键表示输入结束	  
	break;
	cnew=new  Node;;	
	cnew->data=num;	 
	cnew->next=NULL;	
	if(head==NULL)
		//若为空则将头节点指向新节点	 
		head=cnew;
	else	 
	   tail->next=cnew;
	//将当前节点的next指向新的节点	
	tail=cnew;	
   (*numNode)++;	
	}
	return head;}

/*判断是否有环思路概述:分别定义步长为1和2的指针fast and slow
指向头结点,if无环,则fast先走到终点;如果链表长度为奇数时,
fast->Next为空;当链表长度为偶数时,fast为空*/

bool isLoop(pNode  pHead)
{
	pNode fast = pHead;
	pNode slow = pHead;
	while( fast != NULL && fast->next != NULL)
	{
		fast = fast->next->next;
		slow = slow->next;
		//如果有环,则fast会超过slow一圈
		if(fast == slow)
		{
			break;
		}
	}

	if(fast == NULL || fast->next == NULL  )
	{
		cout <<"Wow,there is not loop in the list "<< endl;
		return false;
	}
	else
	{
		cout <<"Yeah,there is loop in the list " << endl;
		return true;
	}
}
int main(int argc ,char * argv[])
{
	int numnode=0;
	//初始化将节点个数初始化为零
   pNode head=NULL ;
   	cout <<"链表head的节点个数为: "  <<endl;
   cin >>numnode;
	head=Create(&numnode);	
    isLoop(head);
	return 0;
}


  • 34
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值