判断单链表中是否环
我的代码
package test;
public class ListNode {
public int node;
public ListNode next;
public ListNode(int node, ListNode next) {
this.node = node;
this.next = next;
}
}
package test;
import java.util.HashMap;
import java.util.Map;
public class LinkList {
static int size;
static ListNode head;
public static void add(ListNode node) {
ListNode temp = head;
if (head == null) {
head = node;
return;
}
while (temp.next != null) {
temp = temp.next;
}
temp.next = node;
}
public void init() {
for (int i = 0; i < 10; i++) {
add(new ListNode(i, null));
}
}
public void makeLoop() {
ListNode temp = head;
while (temp.next != null) {
temp = temp.next;
}
temp.next = head.next.next;
}
public boolean isLoop() {
Map<ListNode, Integer> map = new HashMap<ListNode, Integer>();
ListNode temp = LinkList.head;
size = 1;
while (temp.next != null) {
map.put(temp, size);
if (map.containsKey(temp.next)) {
return true;
} else {
temp = temp.next;
size++;
}
}
return false;
}
}
package test;
public class TestIsLoop {
public static void main(String[] args) {
LinkList linkList = new LinkList();
linkList.init();
linkList.makeLoop();
System.out.println(linkList.isLoop());
System.out.println(LinkList.size);
}
}