java - 如何在链表中制作shuffle方法

标签 java

我正在尝试在我的 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/

相关文章:

基于 Java 的回归测试

java - XMLUnit : How to register a self-closing element as different to a non-self-closing element?

java - 如何使用非对称密码术加密大量数据?

java - 我必须在哪个目录中放置 testng.xml?

java - 如何在 Spring Boot jboss/wildfly 中设置上下文路径?

java - 在方法上使用 @Async 注释时来自 CglibAopProxy 的 NPE

java - JSON对象和JSON数组的管理

java - 如何使这个 SwingWorker 代码可测试

java - PreparedStatement.setQueryTimeout() 不抛出异常

java - 包含同一类/对象的另一个构造函数的构造函数