141.环形链表

1.题目描述:

  给定一个链表,判断链表中是否有环。

2.思路以及代码:

  建立一个哈希表,然后遍历链表,每遍历一个结点就将其加入哈希表中,如果当前结点已存在于哈希表中,存在环形。

  代码如下:

/**
 * 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>set=new HashSet<ListNode>();
            while(head!=null) {
                if(set.contains(head))
                    return true;
                else
                    set.add(head);
                head=head.next;
            }
            return false;
        }
    }

代码参考:力扣官方题解:https://leetcode-cn.com/problems/linked-list-cycle/solution/huan-xing-lian-biao-by-leetcode/

原文地址:https://www.cnblogs.com/teensSpirit-code-life/p/11723066.html