Linked List Cycle

来源:互联网 发布:经济数据公布时间表 编辑:程序博客网 时间:2024/06/06 17:16

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

Follow up:

Can you solve it without using extra space?

定义两个指针,一个快,一个慢,快的追到慢的则存在环。

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

0 0
原创粉丝点击