赞
踩
代码:
- /**
- * Definition for singly-linked list.
- * struct ListNode {
- * int val;
- * struct ListNode *next;
- * };
- */
-
- typedef struct ListNode ListNode;
-
- ListNode* findMidNode(ListNode* head)
- {
- //定义两个指针
- ListNode* slow = head;
- ListNode* fast = head;
- while(fast && fast->next)
- {
- slow = slow->next;
- fast = fast->next->next;
- if(fast == slow)
- return slow;
- }
- return NULL;
- }
-
- struct ListNode *detectCycle(struct ListNode *head) {
- //找环的相遇点
- ListNode* meet = findMidNode(head);
- //从头节点和相遇节点开始遍历,每次走一步
- ListNode* pcur = head;
- while(meet && pcur)
- {
- //当指针相遇的节点,即环的入口节点
- //相遇点和头节点到入环的位置是相等的
- if(meet == pcur)
- {
- return pcur;
- }
- meet = meet->next;
- pcur = pcur->next;
- }
- //代码走到这就说明链表不成环
- return NULL;
- }
提交结果:
那么为什么相遇点和头节点到入环节点的距离是相等的。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。