Linked List Cycle

来源:互联网 发布:电气控制系统设计软件 编辑:程序博客网 时间:2024/05/29 13:34

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

Follow up:

Can you solve it without using extra space?

方法就是两个指针以不同的步长(一个fast一次两个,slow一次一个)遍历链表,如果相等(fast=slow),则链表中存在环。

实现代码如下:

public class Solution {    public boolean hasCycle(ListNode head) {        // IMPORTANT: Please reset any member data you declared, as        // the same Solution instance will be reused for each test case.        ListNode slow = head;        ListNode fast = head;        while(fast != null && fast.next != null)        {            slow = slow.next;            fast = fast.next.next;            if(slow == fast)                return true;        }        return false;    }}


0 0
原创粉丝点击