62,634
社区成员




import java.util.LinkedList;
import java.util.Random;
public class LinkedListTest {
public static void main (String[] args) {
LinkedList<Integer> list = new LinkedList<Integer>();
Random ran = new Random();
Integer i = new Integer(1);
list.add(Math.abs(ran.nextInt()));
list.add(i);
list.add(i);
System.out.println(list);
if (checkValid(list)) System.out.println("It is valid");
else System.out.println("It is invalid");
}
static public boolean checkValid(LinkedList<Integer> list) {
LinkedList<Integer> list1 = (LinkedList<Integer>) list.clone();
System.out.println(list1);
Integer i;
do {
i = list1.removeFirst();
System.out.println(list1);
if (list1.contains((Object) i))
return false;
} while (i != null);
return true;
}
}
import java.util.Random;
class MyNode {
int iValue;
MyNode next;
MyNode (int value) {
System.out.println("add "+ value);
iValue = value;
next = null;
};
public int getValue () {
return iValue;
}
}
class MyList {
int iNum;
MyNode head = null;
public boolean isListValid ()
{
if (head == null) return true;
MyNode p = head;
int i = 0;
while (p.next != null) {
i++;
MyNode c = head;
for(int j = 0; j < i && c != null; j++) {
if (c == p.next) {
return false;
}
else {
c = c.next;
}
}
p = p.next;
}
return true;
}
void add(int value) {
iNum++;
MyNode p = head;
if (p == null) {
head = new MyNode(value);
return;
}
if (isListValid() == false) {
System.out.println("the list has circul node, could not add node into tail");
return;
}
while (p.next != null)
p = p.next;
p.next = new MyNode(value);
}
private void init (int num) {
int i = num;
if (num <= 0) return;
Random ran = new Random(100);
while (i > 0) {
add(Math.abs(ran.nextInt()));
i--;
}
}
private void dump() {
System.out.println("Begin to dump:");
if (!isListValid()) {
System.out.println("the list has circul node, could not add node into tail");
return;
}
MyNode p = head;
while (p != null) {
System.out.println(p.getValue());
p = p.next;
}
}
public void insertInvalidNode() {
if (iNum <= 1) return;
MyNode tail = head;
int i = 0;
while (tail.next != null) {
tail = tail.next;
}
tail.next = head;
}
MyList(int num) {
iNum = num;
init(num);
dump();
}
}
public class ListTest {
public static void main (String[] args) {
MyList list = new MyList(5);
list.insertInvalidNode();
if (list.isListValid() == false) {
System.out.println("the list has circul node, could not add node into tail");
return;
}
}
}