判断链表是否有回环
盗个图
使用新节点
/**
* 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 blank = new ListNode(-1);
ListNode temp = head;
while (head.next != null) {
temp = head.next;
head.next = blank;
head = temp;
}
if (temp == blank) return true;
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;
ListNode slow = head;
ListNode fast = head.next;
while (fast !=null && fast.next != null) {
if (slow == fast) return true;
slow = slow.next;
fast = fast.next..next;
}
return false;
}
}