LeetCode 141:环形链表
题目:
题解:
代码示例:
package com.zy.leetcode.LeetCode_141;
/**
* @Author: zy
* @Date: 2025-01-03-14:09
* @Description: 环形链表
*/
public class ListNode_141 {
private int val;
private ListNode_141 next;
public ListNode_141(int x) {
val = x;
next = null;
}
public static ListNode_141 createList(int[] arr) {
ListNode_141 dummy = new ListNode_141(0);
ListNode_141 cur = dummy;
for (int num : arr) {
cur.next = new ListNode_141(num);
cur = cur.next;
}
return dummy.next;
}
public static void printList(ListNode_141 head) {
ListNode_141 cur = head;
while (cur != null) {
System.out.print(cur.val + " -> ");
cur = cur.next;
}
System.out.println("null");
}
/**
* t兔子一次走两步
* 龟一次走一步
*
* @param node
* @return
*/
private static boolean hasCycle(ListNode_141 node) {
ListNode_141 h = node;//兔
ListNode_141 t = node;// tortoise
while (h != null && h.next != null) {
h = h.next.next;
t = t.next;
if (h == t) {
return true;
}
}
return false;
}
public static void main(String[] args) {
int[] arr = {3, 2, 0, -4, 9, 5};
ListNode_141 head = createList(arr);
printList(head);
System.out.println(hasCycle(head)); // true
//环行链表
ListNode_141 node1 = new ListNode_141(3);
ListNode_141 node2 = new ListNode_141(2);
ListNode_141 node3 = new ListNode_141(0);
ListNode_141 node4 = new ListNode_141(-4);
ListNode_141 node5 = new ListNode_141(9);
ListNode_141 node6 = new ListNode_141(5);
node1.next = node2;
node2.next = node3;
node3.next = node4;
node4.next = node5;
node5.next = node6;
node6.next = node2;
System.out.println(hasCycle(node1)); // true
}
}