判断单链表是否有环

判断单链表是否有环

单链表有环指的是单链表中某个节点的next域指向链表中在它之前的某一个节点,这样在链表的尾部形成一个环形结构。

代码实现

package 剑指offer;

import java.util.HashSet;
import java.util.List;

/**
 * @author WangXiaoeZhe
 * @Date: Created in 2019/11/22 16:55
 * @description:
 */

public class Main13 {
    public static void main(String[] args) {

    }


    class ListNode {
        int val;
        ListNode next;

        ListNode(int x) {
            val = x;
            next = null;
        }
    }

    /**
     * 利用set的性质
     * @param head
     * @return
     */

    public boolean hasCycle(ListNode head){
        /**
         * 创建集合对象
         */

        HashSet<ListNode> set = new HashSet<>();
        /**
         * 遍历链表
         */

        ListNode p=head;
        while(p!=null){
            if (set.contains(p)) {
                return true;
            } else {
                set.add(p);
            }
            p=p.next;
        }
        return false;
    }

    /**
     * 快慢指针遍历法
     */

    public boolean hasCycle2(ListNode head) {
        if (head == null || head.next == null) {
            return false;
        }
        ListNode fast=head;
        ListNode slow=head;
        while (fast != null && fast.next != null) {
            slow=slow.next;
            fast=fast.next.next;
            if (slow == fast) {
                return true;
            }
        }
        return false;
    }

}
posted @ 2019-11-22 17:05  π。  阅读(174)  评论(0编辑  收藏  举报