题目:
判断给出的链表中是否存在环。
思路:
1. 遍历整个链表,将走过的节点的内存地址保存下来,如果再次走到同样的内存地址,说明链表中有环。时间复杂度为O(n)。
2. 设置两个指针,fast指针每次走两步,slow指针每次走一步,
如果链表中有环:
当两个指针都进入环中后,他们将在n次移动后相遇
n = 两只指针之间的距离÷两指针的步速差
如果链表中没有换的话,走的较快的fast指针将会率先链表的尾部。
代码:
import java.util.*; import java.math.*; /** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ class ListNode { int val; ListNode next; ListNode(int x) { val = x; next = null; } } class Solution { /* //HashSet方法 public boolean hasCycle(ListNode head) { Set<ListNode> ListNodeSet = new HashSet<>(); while(head != null){ if(ListNodeSet.contains(head)){ return true; } ListNodeSet.add(head); head = head.next; } return false; }*/ //双指针方法 public boolean hasCycle(ListNode head) { if(head==null || head.next==null){ return false; } ListNode slow = head; ListNode fast = head.next; while(slow != fast){ if(fast.next==null || fast.next.next==null){ return false; } fast = fast.next.next; slow = slow.next; } return true; } } public class Main { public static void main(String[] args){ Scanner scanner = new Scanner(System.in); Solution solution = new Solution(); ListNode list1 = new ListNode(1); ListNode list2 = new ListNode(1); list1.next = list2; ListNode list3 = new ListNode(2); list2.next = list3; ListNode list4 = new ListNode(3); list3.next = list4; ListNode list5 = new ListNode(3); list4.next = list5; list5.next = list5; System.out.println(solution.hasCycle(list1)); } }