Leetcode: Linked List Cycle

来源:互联网 发布:linux 递归查找文件 编辑:程序博客网 时间:2024/06/17 08:33

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

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

Use runner technique. Let runner go twice faster than walker, if they can still meet at certain point, there must be a cycle.

/** * Definition for singly-linked list. * class ListNode { *     int val; *     ListNode next; *     ListNode(int x) { *         val = x; *         next = null; *     } * } */public class Solution {    public boolean hasCycle(ListNode head) {        if (head == null) {            return false;        }                ListNode walker = head;        ListNode runner = head;        while (walker.next != null && runner.next != null && runner.next.next != null) {            walker = walker.next;            runner = runner.next.next;            if (walker == runner) {                return true;            }        }                 return false;    }}


0 0
原创粉丝点击