LeetCode --- 141. 环形链表

/**
 * Definition for singly-linked list.
 * class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
  • 解法1 - 快慢指针

public class Solution {
    public boolean hasCycle(ListNode head) {
        if (head == null) return false;
        ListNode slow = head;
        ListNode fast = head.next;
        while (slow != fast) {
            if (fast == null || fast.next == null) return false;
            slow = slow.next;
            fast = fast.next.next;
        }
        return true;
    }
}
  • 解法2 - 哈希表

public class Solution {
	public boolean hasCycle(ListNode head) {
   	 	Set<ListNode> nodesSeen = new HashSet<>();
   		 while (head != null) {
        	if (nodesSeen.contains(head)) {
            	return true;
       		} else {
            	nodesSeen.add(head);
        	}
       		head = head.next;
   		}
    	return false;
	}
}
发布了188 篇原创文章 · 获赞 19 · 访问量 8万+

猜你喜欢

转载自blog.csdn.net/songzhuo1991/article/details/104200332