首页 > 其他 > 详细

leetcode: Linked List Cycle

时间:2016-07-09 02:09:35      阅读:275      评论:0      收藏:0      [点我收藏+]

问题描述:

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;
    }
}

leetcode: Linked List Cycle

原文:http://shmilyaw-hotmail-com.iteye.com/blog/2309661

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!