我正在尝试在我的 LinkedList 中创建一个随机播放方法。目前,我的洗牌方法是生成一个1到10之间的随机数n,然后取出第n张牌并将其移到前面。然后它将以随机的时间循环。然而,我当前的代码似乎不起作用,因为它所需要的卡只是被删除,而不是把它放在前面。
public void shuffle() {
Node current = head;
int randomX = (int) (Math.random() * 10 + 1);
for (int x = 0; x < randomX; x++) {
int randomY = (int) (Math.random() * 10 + 1);
for (int y = 0; y < randomY; y++) {
if (current.getNext() != null) {
current = current.getNext();
System.out.println("Yup");
System.out.println(current);
System.out.println(y);
}
else {
current = head;
System.out.println("nope");
current = current.getNext();
}
if (current.getPrevious() != null){
current.getPrevious().setNext(current.getNext());
head.setPrevious(current);
current.setPrevious(head);
}
head = current;
}
}
}
最佳答案
确保当您找到要查找的节点时,将其上一个节点的下一个设置为其下一个,并且将节点的下一个上一个设置为其上一个
Node temp = head;
int randomX = (int) (Math.random() * 10 + 1);
//simply go until the randomX
while(randomX-- > 0 && temp.getNext() != null)
temp = temp.getNext();
//remove the Nth node from the list
temp.getPrevious().setNext(temp.getNext());
if(temp.getNext() != null)
temp.getNext().setPrevious(temp.getPrevious());
//set it to point to the head
temp.setNext(head);
temp.setPrevious(null);
//now set the Head to the Nth node we found
head = temp;
关于java - 如何在链表中制作shuffle方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45016281/