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

来源:互联网 发布:shake it off 下载 编辑:程序博客网 时间:2024/05/02 02:44

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

 

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;}


 

 

 

1 0
原创粉丝点击