1. 程式人生 > >leetcode鏈表--6、linked-list-cycle-ii(有環單鏈表環的入口結點)

leetcode鏈表--6、linked-list-cycle-ii(有環單鏈表環的入口結點)

pre you head lis 頭結點 tex -a init int

題目描述 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 };

leetcode鏈表--6、linked-list-cycle-ii(有環單鏈表環的入口結點)