小知识,大挑战!本文正在参与“程序员必备小知识”创作活动。
前言
- 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
}
测试数据准备
public class Test1 {
public static void main (String[] args) throws IOException {
final ListNode listNode = buildNode();
System.out.println("方式一:无限循环:" + test1(listNode));
System.out.println("方式二:hash表:" + test2(listNode));
System.out.println("方式三:双指针:" + test3(listNode));
}
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();
}
}
}
最后