剑指offer 15---判断链表是否带环?若带环求环的长度?若带环求环的入口点?

来源:互联网 发布:图片浏览软件下载 编辑:程序博客网 时间:2024/05/22 08:07

判断链表是否带环?若带环求环的长度?若带环求环的入口点?

判断链表是否带环?

//判断链表是否带环bool IsCircle(ListNode* pHead){if (pHead == NULL || pHead->_next == NULL){return false;}//快慢指针法ListNode* fast = pHead;ListNode* slow = pHead;while (fast->_next->_next != NULL){fast = fast->_next->_next;slow = slow->_next;if (fast == slow)break;}if (fast->_next->_next == NULL)return false;elsereturn true;}



若带环求环的入口点?

//求环的入口点ListNode* MeetNode(ListNode* pHead){if (pHead == NULL || pHead->_next == NULL){return NULL;}ListNode* fast = pHead;ListNode* slow = pHead;while (fast->_next->_next != NULL){fast = fast->_next->_next;slow = slow->_next;if (fast == slow)          //相遇时,即有环{break;}}if (fast->_next->_next == NULL){return NULL;}slow = pHead;while (fast != slow){fast = fast->_next;slow = slow->_next;}return slow;}



若带环求环的长度?

//求环的长度size_t GetCircleLen(ListNode* pHead){ListNode* slow = MeetNode(pHead);     //MeetNode函数中已经判断各种退出的情况,所以在此不再做判断size_t count = 1;ListNode* p = slow->_next;while (p != slow){p = p->_next;++count;}return count;}


完整代码

#include <iostream>#include <assert.h>#include <list>#include <Windows.h>using namespace std;struct ListNode{int _value;ListNode* _next;ListNode(const int& value):_value(value), _next(NULL){}};//求环的入口点ListNode* MeetNode(ListNode* pHead){if (pHead == NULL || pHead->_next == NULL){return NULL;}ListNode* fast = pHead;ListNode* slow = pHead;while (fast->_next->_next != NULL){fast = fast->_next->_next;slow = slow->_next;if (fast == slow)          //相遇时,即有环{break;}}if (fast->_next->_next == NULL){return NULL;}slow = pHead;while (fast != slow){fast = fast->_next;slow = slow->_next;}return slow;}//判断链表是否带环bool IsCircle(ListNode* pHead){if (pHead == NULL || pHead->_next == NULL){return false;}//快慢指针法ListNode* fast = pHead;ListNode* slow = pHead;while (fast->_next->_next != NULL){fast = fast->_next->_next;slow = slow->_next;if (fast == slow)break;}if (fast->_next->_next == NULL)return false;elsereturn true;}//求环的长度size_t GetCircleLen(ListNode* pHead){ListNode* slow = MeetNode(pHead);     //MeetNode函数中已经判断各种退出的情况,所以在此不再做判断size_t count = 1;ListNode* p = slow->_next;while (p != slow){p = p->_next;++count;}return count;}

测试

#include "List.h"void Test(){ListNode* pHead = new ListNode(1);ListNode* cur = pHead;ListNode* p = pHead;ListNode* temp = NULL;for (int i = 2; i <= 10; ++i){temp = new ListNode(i);cur->_next = temp;cur = temp;}cur->_next = pHead->_next;//while (p != NULL)    //该处是为了验证链表是循环的,即有环//{//cout << p->_value << "->";//p = p->_next;//}//cout << endl;/*bool aac = IsCircle(pHead);cout << "链表是否带环: "<< aac << endl;*//*ListNode* tty = MeetNode(pHead);if(tty != NULL){cout << "环的入口点为: " << tty->_value << endl;}*/ size_t ttc = GetCircleLen(pHead);cout << "环的长度为: " << ttc << endl;}int main(){Test();system("pause");return 0;}





阅读全文
1 0