linked-list-cycle

来源:互联网 发布:淘宝网雪纺女装 编辑:程序博客网 时间:2024/05/19 13:55

1、链接: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?

2、思路:设置快慢指针,如果有cycle则会相遇,没有的话,快指针最终会走到tail
3、代码:

public class Solution {    boolean isCycle = false;    public boolean hasCycle(ListNode head) {        ListNode first = head;        ListNode second = head;        while(second != null){            first = first.next;            if(second.next == null)                break;            second = second.next;            second = second.next;            if(first == second){                isCycle = true;                break;            }        }        return isCycle;    }}
原创粉丝点击