【LeetCode】Linked List Cycle II
2014-11-05 22:49
337 查看
题目地址:https://oj.leetcode.com/problems/linked-list-cycle-ii/
解题思路:快慢指针,相遇后快指针回到起点以每次一步走,再次相遇点为环的起点
注意【纯回环】,空链表,无环链表等各种情况
解题思路:快慢指针,相遇后快指针回到起点以每次一步走,再次相遇点为环的起点
注意【纯回环】,空链表,无环链表等各种情况
/** * 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)return null; ListNode fast=head; ListNode low=head; ListNode second=head; boolean hasCycle=false; while(fast!=null&&low!=null){ if(fast.next!=null)fast=fast.next.next; else { break; } low=low.next; if(fast==low){ hasCycle=true; break; } } if(!hasCycle) return null; else{ while(second!=low){ second=second.next; low=low.next; } return low; } } }
相关文章推荐
- LeetCode:Linked List Cycle II
- LeetCode:Linked List Cycle II
- LeetCode | Linked List Cycle II
- LeetCode | Linked List Cycle II
- LeetCode之Linked List Cycle II
- leetcode - Linked List Cycle II
- [Leetcode 141 & 142, medium] Linked List Cycle (I and II)
- [LeetCode] - Linked List Cycle II
- [leetcode]Linked List Cycle II
- LeetCode: Linked List Cycle II
- [算法][LeetCode]Linked List Cycle & Linked List Cycle II——单链表中的环
- [LeetCode] Linked List Cycle II
- Leetcode: Linked List Cycle II
- [LeetCode]Linked List Cycle II
- [leetcode]Linked List Cycle II
- Leetcode Linked List Cycle II
- leetcode: Linked List Cycle II
- Leetcode: Linked List Cycle II
- LeetCode - Linked List Cycle II
- leetcode Linked List Cycle II