赞
踩
分析:如果链表中有环,快慢指针肯定能相遇,这个非常容易证明,而且相遇肯定是在环中.
快指针走的倍数是慢指针两倍,这样可以非常容易得出循环的开始结点
/** * Definition for singly-linked list. * struct ListNode { * int val; * struct ListNode *next; * }; */ /** * Definition for singly-linked list. * struct ListNode { * int val; * struct ListNode *next; * }; */ struct ListNode *detectCycle(struct ListNode *head) { //直接判断是否没有结点,或者只有一个节点,直接返回 if(head==NULL||head->next==NULL){ return NULL; } //申请快慢指针,快指针是慢指针走的倍数是两倍 struct ListNode *slow=head; struct ListNode *fast=head; while(fast!=NULL&&fast->next!=NULL){ slow=slow->next; fast=fast->next->next; //两指针相遇说明有环,namename就可以开始把其中一个指针初始为头,然后开始一步一步走直到相遇,返回相遇的结点就行 if(fast==slow){ fast=head; while(fast!=slow){ fast=fast->next; slow=slow->next; } return slow; } } return NULL; }
/** * Definition for singly-linked list. * class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */ public class Solution { public ListNode detectCycle(ListNode head) { if(head==null||head.next==null) return null; ListNode slow=head; ListNode fast=head; while(fast!=null&&fast.next!=null){ fast=fast.next.next; slow=slow.next; if(fast==slow){ fast=head; while(fast!=slow){ fast=fast.next; slow=slow.next; } return fast; } } return null; } }
还是直接套套路就行.
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。