141. Linked List Cycle

来源:互联网 发布:数据化人生txt 编辑:程序博客网 时间:2024/05/16 05:12

题目:https://leetcode.com/problems/linked-list-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) {        HashSet<ListNode> m = new HashSet<>();        if(head==null||head.next==null)            return false;        while(head!=null)        {            if(m.contains(head))                return true;            m.add(head);            head = head.next;        }        return false;    }}11ms=================================/** * 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 || head.next == null)             return false;        ListNode p = head;        ListNode q = head;        while(q != null && q.next != null) {            p = p.next;            q = q.next.next;            if (p == q)                return true;        }        return false;    }}1ms
0 0
原创粉丝点击