【leetcode】【141】Linked List Cycle

来源:互联网 发布:北京精雕编程系统 编辑:程序博客网 时间:2024/05/16 00:50

一、问题描述

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

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

二、问题分析

典型的two points问题,通过设置快慢指针,如果有环,那么快指针总会追上慢指针;如果不存在环,那么快指针会先指向null。

三、Java AC代码

public boolean hasCycle(ListNode head) {        if (head == null || head.next == null) {return false;}ListNode slow = head;ListNode fast = head;while (fast!=null && fast.next != null) {fast = fast.next.next;slow = slow.next;if (fast == slow) {return true;}}return false;    }


0 0
原创粉丝点击