码迷,mamicode.com
首页 > 编程语言 > 详细

C++ 算法之 是否为环形链表

时间:2014-12-16 17:13:12      阅读:154      评论:0      收藏:0      [点我收藏+]

标签:blog   ar   io   os   sp   2014   log   bs   代码   

如果有两个头结点指针,一个走的快,一个走的慢,那么若干步以后,快的指针总会超过慢的指针一圈。

 

bool IsCycleList(ListNode* pHead)
{
	if(pHead== NULL) 
		return false;
	if (pHead->m_pNext == NULL)
	{
		return false;
	}
	ListNode* pFastNode   = pHead;
	ListNode* pSlowNode  = pHead;

	//如果为偶数个,pFastNode->m_pNext->m_pNext为空;如果为奇数个,pFast->m_pNext为空;
	while(pFastNode->m_pNext != NULL && pFastNode->m_pNext->m_pNext != NULL)
	{
		pFastNode = pFastNode->m_pNext->m_pNext;
		pSlowNode = pSlowNode->m_pNext;
		if (pSlowNode == pFastNode)
		{
			break;
		}
	}
	if (pFastNode == NULL || pFastNode->m_pNext == NULL)
	{
		return false;
	}
	else
	{
		return true;
	}
}


完整代码测试:

// CycleList.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <iostream>
using namespace  std;

struct ListNode 
{
	int       m_nValue;
	ListNode* m_pNext;
	ListNode(int k):m_nValue(k),m_pNext(NULL)
	{

	}
};

bool IsCycleList(ListNode* pHead)
{
	if(pHead== NULL) 
		return false;
	if (pHead->m_pNext == NULL)
	{
		return false;
	}
	ListNode* pFastNode   = pHead;
	ListNode* pSlowNode  = pHead;

	//如果为偶数个,pFastNode->m_pNext->m_pNext为空;如果为奇数个,pFast->m_pNext为空;
	while(pFastNode->m_pNext != NULL && pFastNode->m_pNext->m_pNext != NULL)
	{
		pFastNode = pFastNode->m_pNext->m_pNext;
		pSlowNode = pSlowNode->m_pNext;
		if (pSlowNode == pFastNode)
		{
			break;
		}
	}
	if (pFastNode == NULL || pFastNode->m_pNext == NULL)
	{
		return false;
	}
	else
	{
		return true;
	}
}


int _tmain(int argc, _TCHAR* argv[])
{

	ListNode* head  = new ListNode(1);
	ListNode* Node1 = new ListNode(2);
	ListNode* Node2 = new ListNode(3);
	ListNode* Node3 = new ListNode(4);
	ListNode* Node4 = new ListNode(5);
	ListNode* Node5 = new ListNode(6);
	ListNode* Node6 = new ListNode(7);


	head->m_pNext = Node1;
	Node1->m_pNext = Node2;
	Node2->m_pNext = Node3;
	Node3->m_pNext = Node4;
	Node4->m_pNext = Node5;
	Node5->m_pNext = Node6;
	Node6->m_pNext = head;

	bool b = IsCycleList(head);
	cout<<b<<endl;

	getchar();

	return 0;
}


 

 

 

C++ 算法之 是否为环形链表

标签:blog   ar   io   os   sp   2014   log   bs   代码   

原文地址:http://blog.csdn.net/djb100316878/article/details/41960985

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!