java - 如何在java中打乱链表

标签 java linked-list

我一生都无法弄清楚为什么这种随机播放方法不起作用:

public void deckShuffle(int shuffle) {
    Random rand = new Random();
    int targetCard, cardValue, cardSuit;
    Card temp, card;

    for (int x = 0; x < shuffle; x++) {
    for(int y = 1; y < 52; y++) {
            targetCard = 51 - rand.nextInt(51);
            temp = getCard(targetCard);
            cardValue = temp.getCardValue();
            cardSuit = temp.getCardSuit();
            removeCard(targetCard);
            addLast(cardValue, cardSuit);
    }
}

这是我删除卡并添加最后的代码:

public void removeCard(int index) {

    if (head.next == null || index < 1) {return;}

    if (count > 0 && index <= count) {
        Card current = head;

        for (int x = 0; x < index; x++) {
            current = current.next;
        }

        current.next = current.next.next;
        count--;
    }
}




public void addLast(int cardValue, int cardSuit) {
    Card temp = new Card(cardValue, cardSuit, null);        
    Card current = head; // POINTER

    while (current.next != null) {
        current = current.next;
    }

    current.next = temp;
    count++;
}

我试图找出为什么代码不起作用。当我运行一种方法来打印一副 52 张牌并洗牌时,所有牌都显示为 2 颗红心。我知道这不是我的构建方法,因为我在编写 shuffle 方法之前对其进行了测试。

我明白了,伙计们。我的移除卡方法无法正常工作,但现在可以正常洗牌了。感谢您的帮助!

最佳答案

为什么不直接使用Collections.shuffle方法呢?

有关更多信息,也许您应该发布您的 Card 类?那么至少有人可以尝试运行代码(如果他们愿意的话)。

关于java - 如何在java中打乱链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28683908/

相关文章:

java - Spring引导自动配置无法将属性文件从jar绑定(bind)到bean

list - Golang 中 LinkedList<T> 的等价物是什么

c - C 中存储字符串的链表或数组

java - for 循环在已编译的类文件中转换为 do while 循环

java - HttpClient : disabling chunked encoding

在每个数据字段中复制一个数组到链表

C插入链表,第一个和最后一个节点的问题

java - 访问由私有(private)自定义类组成的链表的元素

java - File[] 无法处理多个文件

java - 关于使用 openJPA MySQL 进行运行时优化的异常