判断单链表是否带环
Posted ssopp24
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了判断单链表是否带环相关的知识,希望对你有一定的参考价值。
//这个题思路不难,我们只要定义两个指针,一快一慢,快指针一次走两步,慢指针一次走一步
//如果它们相遇,则单链表构成了环形结构。 如果未相遇, 而快指针走到了链表结尾,则单链表未构成环形结构
#include <iostream>
using namespace std;
struct ListNode
int m_nKey;
ListNode* m_pNext;
ListNode( ListNode* pNext, int value )
: m_pNext( pNext )
, m_nKey( value )
;
bool IsRing( ListNode* pListHead );
void push_back( ListNode** pHead, int value );
ListNode* Find( ListNode* pListHead, int value );
int main( )
ListNode* pHead = NULL;
//push_back( &pHead, 1 );
//push_back( &pHead, 2 );
//push_back( &pHead, 3 );
//push_back( &pHead, 4 );
//push_back( &pHead, 5 );
push_back( &pHead, 1 );
push_back( &pHead, 2 );
push_back( &pHead, 3 );
push_back( &pHead, 4 );
push_back( &pHead, 5 );
ListNode* pNode3 = Find( pHead, 3 );
ListNode* pNode5 = Find( pHead, 5 );
pNode5->m_pNext = pNode3;
cout << IsRing( pHead );
return 0;
void push_back( ListNode** pHead, int value )
if ( NULL == pHead )
return;
ListNode* pNewNode = new ListNode( NULL, value );
if ( NULL == *pHead )
*pHead = pNewNode;
return;
ListNode* pNode = *pHead;
while ( NULL != pNode->m_pNext )
pNode = pNode->m_pNext;
pNode->m_pNext = pNewNode;
ListNode* Find( ListNode* pListHead, int value )
if ( NULL == pListHead )
return NULL;
ListNode* pNode = pListHead;
while ( NULL != pNode && value != pNode->m_nKey )
pNode = pNode->m_pNext;
if ( NULL == pNode )
return NULL;
return pNode;
//以后写代码,一定不要忘了考虑边界情况
bool IsRing( ListNode* pListHead )
if ( NULL == pListHead )
return false;
ListNode* pFast= pListHead;
ListNode* pSlow= pListHead;
while ( NULL != pFast->m_pNext )
if ( NULL != pFast->m_pNext->m_pNext )
pFast = pFast->m_pNext->m_pNext;
pSlow = pSlow->m_pNext;
else
return false;
if ( pSlow == pFast )
return true;
return NULL;
以上是关于判断单链表是否带环的主要内容,如果未能解决你的问题,请参考以下文章