小知识,大挑战!本文正在参与“程序员必备小知识”创作活动。
前言
- LeetCode算法第141题,是判断环形链表。
- 其实这题算是比较简单,思路也不复杂,这次就把Java的代码简单实现一下。
方式一:无限循环
/**
* 方式一:无限循环
*/
private static boolean test1 (ListNode head) {
int i = 0;
boolean fal = false;
ListNode next = head;
while (next != null) {
if (i > 10000000) {
fal = true;
break;
}
i++;
next = next.next;
}
return fal;
}
复制代码
方式二:hash表
private static boolean test2 (ListNode head) {
Set<ListNode> set = new HashSet<>();
boolean fal = false;
ListNode next = head;
while (next != null) {
if (set.contains(next)) {
fal = true;
break;
}
set.add(next);
next = next.next;
}
return fal;
}
复制代码
方式三:双指针
/**
* 方式三:双指针
*/
private static boolean test3 (ListNode head) {
boolean fal = false;
// 快、慢指针
ListNode index = head;
ListNode next = head;
while (next != null) {
ListNode toIndex;
if (null == index || (toIndex = index.next) == null || (index = toIndex.next) == null) {
break;
}
next = next.next;
if (next == index) {
fal = true;
break;
}
}
return fal;
}
复制代码
测试数据准备
/**
* 判断链表是否有环
*
* @Author: ZRH
* @Date: 2021/10/9 13:57
*/
public class Test1 {
/**
* 方式一:无限循环
* 方式二:hash表
* 方式三:双指针
*
* @param args
*/
public static void main (String[] args) throws IOException {
final ListNode listNode = buildNode();
// 方式一:无限循环
System.out.println("方式一:无限循环:" + test1(listNode));
// 方式二:hash表
System.out.println("方式二:hash表:" + test2(listNode));
// 方式三:双指针
System.out.println("方式三:双指针:" + test3(listNode));
}
/**
* 构建链表结构
*
* @return
*/
private static ListNode buildNode () {
ListNode first = new ListNode(1);
ListNode next = first;
ListNode linkListNode = null;
for (int i = 2; i < 100000; i++) {
ListNode listNode = new ListNode(i);
next.setNext(listNode);
next = listNode;
if (i == 70000) {
linkListNode = listNode;
}
}
// 随机制作环
next.setNext(linkListNode);
return first;
}
/**
* 自定义链表节点
*/
@Data
private static class ListNode {
private ListNode next;
private Integer value;
public ListNode (Integer value) {
this.value = value;
}
@Override
public int hashCode () {
return value.hashCode();
}
}
}
复制代码
最后