Leetcode 141. 环形链表

141. 环形链表

题目

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

进阶:

你能否不使用额外空间解决此题?

思路

1) 采用额外空间,使用 hashset

2)采用快慢指针

代码

  1. 采用 hashset
public class Solution {
    public boolean hasCycle(ListNode head) {
                if(head == null)
            return false;

        HashSet<ListNode> set = new HashSet<>();

        while (head!=null){

            if (set.contains(head)){
                return true;
            }
            else {
                set.add(head);
                head = head.next;
            }
        }
        return false;
    }
}
  1. 采用双指针

代码

采用双指针查找,时间性能更好

/**
 * 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 slowIndex = head;
        ListNode fastIndex =head;

        while (fastIndex!= null && fastIndex.next !=null){
            slowIndex = slowIndex.next;
            fastIndex =fastIndex.next.next; //如果当前节点数不足的话,最终会指向 null

            if (slowIndex == fastIndex){
                return true;
            }
        }
        return false;   
    }
}
posted @ 2018-04-24 15:23  HuanChen1025  阅读(152)  评论(0编辑  收藏  举报