如何在链表中创建一个shuffle方法

时间:2017-07-10 15:40:37

标签: java

我正在尝试在LinkedList中创建一个shuffle方法。目前,我的改组方法是生成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;
            }
        }


    }

2 个答案:

答案 0 :(得分:2)

确保当您找到要查找的节点时,将上一个节点的下一个设置为下一个节点并将节点设置为下一个节点到之前的

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;

答案 1 :(得分:0)

看起来你的move the randomly chosen node to head放错了地方。它应该是外部选择要移动的循环。

一些评论会使这一点显而易见。

public void shuffle() {
    Node current = head;
    // How many times to shuffle.
    int randomX = (int) (Math.random() * 10 + 1);
    // Move random node to head random number of times.
    for (int x = 0; x < randomX; x++) {
        // Pick the one to move.
        int randomY = (int) (Math.random() * 10 + 1);
        // Go find it.
        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 {
                // Hit end of list - go back to start.
                current = head;
                System.out.println("nope");
                current = current.getNext();

            }
        }
        // Bring the chosen one to `head` - **** I moved this OUTSIDE the loop above.
        if (current.getPrevious() != null) {
            current.getPrevious().setNext(current.getNext());
            head.setPrevious(current);
            current.setPrevious(head);

        }
        head = current;
    }
}