美文网首页
Linked List Cycle

Linked List Cycle

作者: ab409 | 来源:发表于2015-11-19 20:01 被阅读43次

Linked List Cycle


今天是一道有关链表的题目,来自LeetCode,难度为Medium,Acceptance为36.6%

题目如下

Given a linked list, determine if it has a cycle in it.
Example
Given -21->10->4->5, tail connects to node index 1, return true
Challenge
Follow up:
Can you solve it without using extra space?

解题思路及代码见阅读原文

回复0000查看更多题目

解题思路

首先,该题虽然是Medium,但是通过率达到36.6%,可见很多同学都见过这道题,所有我也不会过多解释。

那么,思路是怎样的呢。其实很简单,见过该题的同学肯定也知道:因为这里是一个单项链表,如果没有环,那么最后一个元素的next必定指向null;所以我们可以用一个快指针、一个慢指针,快指针一次走两步,慢指针一次走一步,这样如果快指针最后指向了null,那么肯定是没有环;如果快指针最后追上了慢指针即有环。

最后,就是考虑循环的终止条件,很显然即快指针是否指向null

代码如下

java版

/**
 * Definition for ListNode.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int val) {
 *         this.val = val;
 *         this.next = null;
 *     }
 * }
 */ 
public class Solution {
    /**
     * @param head: The first node of linked list.
     * @return: True if it has a cycle, or false
     */
    public boolean hasCycle(ListNode head) {  
        // write your code here
        ListNode fast = head, slow = head;
        while(fast != null && fast.next != null){
            fast = fast.next.next;
            slow = slow.next;
            if(fast == slow)
                return true;
        }
        return false;
    }
}

相关文章

网友评论

      本文标题:Linked List Cycle

      本文链接:https://www.haomeiwen.com/subject/bvylhttx.html