【发布时间】:2012-07-13 02:07:05
【问题描述】:
我正在尝试随机打乱列表。每次我尝试测试代码时,它基本上什么都不做,也没有结束。我想知道我到底错过了什么或做错了什么。
public static ListElement shuffle(ListElement head){
int n= ListUtils.getLength(head);
ListElement head2= null;
while( head != null) {
int random = (int) Math.random() * n;
for(int i=0;i<random;i++){
ListElement list= new ListElement();
list=getItem(head2,n);
list.getNext();
head2=list;
}
}
return head2;
}
获取项目
public static ListElement getItem(ListElement head, int n){
if(n == 0){
return head;
}else if(head == null){
return null;
}else{
return getItem(head.getNext(),n-1);
}
}
【问题讨论】:
-
只要使用
java.util.Collections.shuffle(myList) -
getItem()的代码在哪里? -
我需要使用 Math.random() 因为我想学习如何使用它。
-
在
head != null和list总是null的条件下可能会导致无限循环,因为您永远不会更新将发送到getItem()的head2变量。 -
如果您想要更好的熵和更独特的随机数,请考虑使用 SecureRandom。
标签: java random linked-list shuffle