题目描述
Given a linked list, return the node where the cycle begins. If there is no cycle, returnnull.
Follow up:
Can you solve it without using extra space?
解题思路:
1、确定环中结点的数目(快慢指针确定环中结点,然后遍历到下一次到该节点确定数目n)
2、一个指针先走n步,一个指针指向头结点
3、然后两个指针一起走
4、相遇点为入口点
1 /** 2 * Definition for singly-linked list. 3 * struct ListNode { 4 * int val; 5 * ListNode *next; 6 * ListNode(int x) : val(x), next(NULL) {} 7 * }; 8 */ 9 class Solution { 10 public: 11 //1、确定环中结点数目n 12 //2、两个指针 1个先走n步,然后两个一起走 13 //3、相遇点即为入口点 14 ListNode *detectCycle(ListNode *head) { 15 if(head == NULL) 16 return NULL; 17 ListNode *node = MettingNode(head); 18 if(node == NULL)//无环 19 { 20 return NULL; 21 } 22 int nodeNum = 1; 23 ListNode *pNode = node; 24 while(pNode->next != node) 25 { 26 pNode =pNode->next; 27 nodeNum++; 28 } 29 pNode = head;//pNode指向头结点 30 for(int i=0;i<nodeNum;i++) 31 { 32 pNode = pNode->next; 33 } 34 ListNode *pNode2 = head; 35 while(pNode2 != pNode)//两结点不相遇 36 { 37 pNode = pNode->next; 38 pNode2 = pNode2->next; 39 } 40 return pNode; 41 } 42 //快慢指针找环中相遇结点 43 //找到相遇节点就可确定环中结点数目 44 ListNode *MettingNode(ListNode *head) 45 { 46 if(head == NULL) 47 return NULL; 48 ListNode *slow = head; 49 ListNode *fast = head; 50 while(fast != NULL && fast->next != NULL) 51 { 52 slow = slow->next; 53 fast = fast->next->next; 54 if(slow == fast) 55 return slow; 56 } 57 return NULL; 58 } 59 };