本文共 2441 字,大约阅读时间需要 8 分钟。
将每次遍历的节点加入set集合 如果有重复的节点就不可以加入
/** * 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; } //创建一个set集合 Setset = new HashSet<>(); //遍历所有节点 将节点加入集合 加入失败说明有环 while(head != null) { if(!set.add(head)) { return true; } head = head.next; } return false; }}
/** * 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 || head.next == null) { return false; } //采用快慢指针的方式解题,如果有环,快慢指针会再次相遇 //慢指针一次走一步 快指针一次走两步 //首先创建两个指针 这里不能让快慢指针从同一位置开始 不会进入while循环 ListNode fast = head.next; ListNode slow = head; //遍历链表 如果两者没相遇就一直遍历 没到链表的末尾就一直遍历 while(slow != fast) { //在遍历的过程中 如果遍历到了末尾就表示没有环 fast跑的快 只需要对fast进行判断 if(fast == null || fast.next == null || fast.next.next == null) { return false; } slow = slow.next; fast = fast.next.next; } //退出while循环说明相遇 就有环 return true; }}
/** * 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 || head.next == null) { return false; } //采用快慢指针的方式解题,如果有环,快慢指针会再次相遇 //慢指针一次走一步 快指针一次走两步 //首先创建两个指针 这里不能让快慢指针从同一位置开始 不会进入while循环 ListNode fast = head.next; ListNode slow = head; //遍历链表 如果两者没相遇就一直遍历 没到链表的末尾就一直遍历 while(fast != null && fast.next != null && fast.next.next != null) { //相遇 说明有环 if(fast == slow) { return true; } slow = slow.next; fast = fast.next.next; } //退出while循环说明相遇 就有环 return false; }}
转载地址:http://ilhzi.baihongyu.com/