算法系列——Linked List Cycle

来源:互联网 发布:淘宝店招在线设计 编辑:程序博客网 时间:2024/06/04 20:27

题目描述

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

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

解题思路

题目要求是判断链表是否存在环。解决方法是采用快慢双指针,
一个一次前进一部,另一个前进两部,如果链表存在环,两个指针一定会相遇。

程序实现

public class Solution {    public boolean hasCycle(ListNode head) {        if(head==null)            return false;        ListNode p1=head;        ListNode p2=head;        //快指针作为循环判断条件        while(p2!=null&&p2.next!=null){            p1=p1.next;            p2=p2.next.next;            if(p1==p2)                return true;        }        return false;    }}
原创粉丝点击