62,614
社区成员
发帖
与我相关
我的任务
分享
class Node{
Node next;
}
class Node
{
Node next;
int value;
}
public class Main {
public static boolean isCircle(Node head) {
Node s1 = head.next;
while(s1 != null){
if(s1 == head){
return true;
}
s1 = s1.next;
}
return false;
}
}
package com.future.pang;
public class Node {
// 指向下一节点
private Node next = null;
// 存储数据
private Object obj = null;
// 判断节点是不是最后一个
public boolean hasNext()
{
return next==null?false:true;
}
// 下一个节点
public Node next()
{
return this.getNext();
}
// 添加数据
public void add(Object obj)
{
this.obj = obj;
}
// 设置节点
public void setNext(Node node)
{
this.next = node;
}
// 获得节点,同next()方法一样
public Node getNext()
{
return this.next;
}
}
class Node
{
Node next;
int value;
}
public class Main {
public static void printLinkedList(Node head) {
Node current = head;
while (current != null) {
System.out.print(current.value);
current = current.next;
System.out.print(" ");
}
}
//IMPORTANT!
public static boolean circleLinkedList(Node head) {
Node s1 = head.next;
Node s2 = (head.next != null) ? head.next.next : null;
while (s1 != s2) {
if (s1 == null || s1.next == null || s2 == null || s2.next == null)
return false; //Has the tail
s1 = s1.next;
s2 = s2.next.next;
}
return true;
}
public static void main(String[] args) {
Node head = null;
Node current = null;
Node n5 = null;
for (int i = 0; i < 10; i++)
{
Node n = new Node();
if (head != null) {
n.value = i;
current.next = n;
current = n;
} else {
head = n;
current = n;
current.next = null;
current.value = i;
}
if (i == 5) {
n5 = current;
}
}
printLinkedList(head);
current.next = n5;
System.out.println(circleLinkedList(head));
}
}