LeetCode 141. circular linked list (Java)

  1. Circular linked list

Given a list, the list is determined whether a ring.
To show the list given ring, we integer pos connected to the end of the list to represent the position of the list (index starts from 0). If pos is -1, the ring is not on this list.

Example 1:
Input: head = [3,2,0, -4] , pos = 1
Output: true
explanation: the list has a ring tail portion connected to a second node.

Source: stay button (LeetCode)
link: https: //leetcode-cn.com/problems/linked-list-cycle
copyrighted by deduction from all networks. Commercial reprint please contact the authorized official, non-commercial reprint please indicate the source.

Knowledge Point: Set inherited from the Collection interface, it is not allowed to duplicate elements, and unordered collections, there are two HashSet and TreeSet implementation class.

Thinking: a new hash table, each node into the hash table, if repeated, then prove ring

/**
 * 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) {
        //Set继承于Collection接口,是一个不允许出现重复元素,并且无序的集合,主要有HashSet和TreeSet两大实现类。
        Set<ListNode> nodesSeen = new HashSet<>();
        while(head!=null)
        {
            if(nodesSeen.contains(head))
            {
                return true;
            }
            else
            {
                nodesSeen.add(head);
            }
            head=head.next;
        }
        return false;
    }
}
Published 36 original articles · won praise 0 · Views 410

Guess you like

Origin blog.csdn.net/nuts_and_bolts/article/details/104806999
Recommended