判断单链表是否带环(某公司实习生招聘笔试试题)

#include<iostream>
using namespace std;

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

Node *createList(int n)
{
	Node *p = new Node[n];
	for( int i = 1; i < n; ++i)
	{
		p[i - 1].next = &p[i];
		p[i - 1].data = i;
	}
	p[n - 1].next = NULL;
	p[n - 1].data = n;
	return p;
}

Node *createListWithRing(int n)
{
	Node *p = new Node[n];
	for( int i = 1; i < n; ++i)
	{
		p[i - 1].next = &p[i];
		p[i - 1].data = i;
	}
	p[n - 1].next = &p[n/2];
	p[n - 1].data = n;
	return p;
}

//pFast相当于摩托车,pSlow相当于自行车
//摩托车在前,自行车在后,如果还能相遇,则必然有环
bool listHasRing(Node *p)
{
	Node *pSlow = &p[0];
	Node *pFast = &p[1];
	while(NULL != pSlow && NULL != pFast -> next) // 经网友提醒,在使用p->next之前一定要检查p, 下面类似。感谢网友。
	{
		if(pSlow == pFast)
			return true;
		pSlow = pSlow -> next;
		pFast = pFast -> next ->next;
	}
	return false;
}

void print(bool b)
{
	if(b)
		cout << "There is a ring in the list." << endl;
	else
		cout << "There is no ring in the list." << endl;
}

int main()
{
	int n = 10;
	Node *head = createList(n);
	print(listHasRing(head));
	delete [] head; 

	head = createListWithRing(10);
	print(listHasRing(head));
	delete [] head; 
	return 0;
}


 

评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值