首页 > 代码库 > C++ 算法之 是否为环形链表
C++ 算法之 是否为环形链表
如果有两个头结点指针,一个走的快,一个走的慢,那么若干步以后,快的指针总会超过慢的指针一圈。
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++ 算法之 是否为环形链表
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。