码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode]141. Linked List Cycle

时间:2018-03-05 11:14:41      阅读:181      评论:0      收藏:0      [点我收藏+]

标签:lower   oid   next   eth   思路   []   list   desc   turn   

题目描述:

Given a linked list, determine if it has a cycle in it.

Follow up:
Can you solve it without using extra space?

 思路:

判断一个链表是否有环。
* 同个时间Faster走的比Slower走的多。一般来说,Slower每次走一步,Faster每次走2步(通常这个概念可以判断链表中间点)。
* 在这里,Faster和Slower同时从起点遍历链表,如果有环那么Slower和Faster肯定会相遇。
* 快慢指针问题,设置两个ListNode, Faster = Slower = head;Slower.next = Slower.next;Faster.next = Faster.next.next;
* 假设Faster确实把Slower超了而且他俩还没相遇(类似Faster一下迈了2步,Slower一下迈了一步,Faster超了Slower,但是俩人并没遇上)。
* 那么就假设Faster现在在 i+1 位置而Slower在 i 位置。那么前一时刻,Slower肯定是在 i-1 位置,而Faster肯定在(i+1)-2位置,所以前一时刻,
* 俩人都在 i-1 位置,相遇了。
* 还有一种情况就是Faster在i+2位置而slower在i位置,那么前一时刻,Faster在i位置,而Slower在 i-1位置。
* 这样问题又回归到上面那种情况了(再往前一时刻,Faster在i-2位置,Slower在i-1-1位置,相遇)。
* 所以,这就证明Runner和Faster在有环的链表中肯定会相遇。

 1 /**
 2  * Definition for singly-linked list.
 3  * class ListNode {
 4  *     int val;
 5  *     ListNode next;
 6  *     ListNode(int x) {
 7  *         val = x;
 8  *         next = null;
 9  *     }
10  * }
11  */
12 
13 public class Solution141 {
14      public boolean hasCycle(ListNode head) {
15             if(head == null) return false;
16             ListNode faster = head;
17             ListNode slower = head;
18             while(faster.next!=null && faster.next.next!=null){
19                 faster = faster.next.next;
20                 slower = slower.next;
21                 if(faster==slower){
22                     return true;
23                 }
24             }
25             return false;
26         }
27     public static void main(String[] args) {
28         // TODO Auto-generated method stub
29 
30     }
31 
32 }

 

[LeetCode]141. Linked List Cycle

标签:lower   oid   next   eth   思路   []   list   desc   turn   

原文地址:https://www.cnblogs.com/zlz099/p/8507540.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!