leetcode: Linked List Cycle

问题描述:

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

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

原问题链接:https://leetcode.com/problems/linked-list-cycle/

问题分析

  这是一个比较老的问题了。要判断一个链表是否存在有环,一种办法就是采用快慢指针的方式。一个向前移动一步,一个向前移动两步。这样只要存在有环这个快指针就一定可以遇到慢指针。这样也就证明了链表存在环。

  在实际实现的时候还需要考虑到链表不存在环的情况,因为一个指针一次是移动一步,一个是向前移动两步,这样就很容易导致这个移动快的指针移动一步的时候就已经指向null了。所以这里要加一个second.next != null的判断。详细的实现如下:

/**
 * Definition for singly-linked list.
 * class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public boolean hasCycle(ListNode head) {
        if(head == null || head.next == null) return false;
        ListNode first = head, second = head;
        while(first != null && second != null && second.next != null) {
            first = first.next;
            second = second.next.next;
            if(first == second) return true;
        }
        return false;
    }
}

猜你喜欢

转载自shmilyaw-hotmail-com.iteye.com/blog/2309661
今日推荐