如何在链表中混洗节点?

时间:2013-03-23 14:43:56

标签: data-structures linked-list nodes shuffle

我刚刚为我的Java2课程开始了一个项目,我已经完全停下来了。我无法得到 我围绕这个方法。特别是当赋值不允许我们使用任何其他数据结构或来自java的shuffle方法时。

所以我有一个Deck.class,我已经在其中创建了一个包含52个节点的链表,其中包含52张卡片。

public class Deck {

    private Node theDeck;
    private int numCards;

    public Deck () 
    {
        while(numCards < 52)
        {
            theDeck = new Node (new Card(numCards), theDeck);
            numCards++;
        }
    }

    public void shuffleDeck()
    {           
        int rNum;
        int count = 0;
        Node current = theDeck;
        Card tCard;
        int range = 0;  

        while(count != 51)
        {   
            // Store whatever is inside the current node in a temp variable
               tCard = current.getItem();

            // Generate a random number between 0 -51      
                rNum = (int)(Math.random()* 51);

            // Send current on a loop a random amount of times
               for (int i=0; i < rNum; i ++)
                current = current.getNext();   ******<-- (Btw this is the line I'm getting my error, i sort of know why but idk how to stop it.)

            // So wherever current landed get that item stored in that node and store it in the first on
            theDeck.setItem(current.getItem());

            // Now make use of the temp variable at the beginning and store it where current landed
            current.setItem(tCard);

            // Send current back to the beginning of the deck
            current = theDeck;

            // I've created a counter for another loop i want to do     
            count++;

            // Send current a "count" amount of times for a loop so that it doesn't shuffle the cards that have been already shuffled.   
            for(int i=0; i<count; i++)
             current = current.getNext();  ****<-- Not to sure about this last loop because if i don't shuffle the cards that i've already shuffled it will not count as a legitimate shuffle? i think? ****Also this is where i sometimes get a nullpointerexception****

        }

    }

}

现在我遇到了不同类型的错误 当我打电话给这个方法时:

  • 它有时会洗掉2张牌,但有时它会洗牌3到5张卡然后给我一个NullPointerException。 我已经在上面的代码

  • 中指出它在哪里给我这个错误的星号
  • 在某一点上,我得到它来洗牌13张牌,但是每当它做到这一点时,它并没有以正确的方式洗牌。一张卡一直在重复。

  • 在另一点上,我得到了所有52张卡片通过while循环,但又一次重复了一张卡片。

所以我真的需要一些输入,因为我做错了。在我的代码结束时,我认为我的逻辑是完全错误的,但我似乎无法找到解决方法。

5 个答案:

答案 0 :(得分:2)

似乎很啰嗦。

我会选择以下内容:

public void shuffleDeck() {
    for(int i=0; i<52; i++) {
        int card = (int) (Math.random() * (52-i));
        deck.addLast(deck.remove(card));
    }
}

因此,每张卡片都会以随机顺序移动到牌组的后面。

答案 1 :(得分:0)

如果您被授权使用辅助数据结构,一种方法是简单地计算剩余卡数内的随机数,选择该卡,将其移动到辅助结构的末尾直到空,然后替换您的列表与次要清单。

答案 2 :(得分:0)

所以我终于想出来了,这是我对shuffle方法的更新

public void shuffleDeck()
{           

    Node current;
    Node random;
    Card cTemp;
    int rand;

    rand = (int)(Math.random() * numCards);

    for (int j=0; j<rand; j++)
    {
        for (int i=0; i<numCards; i++)
        {
            current = theDeck;
            random = theDeck;

            rand = (int)(Math.random() * numCards);

            for(int k = 0; k < rand; k++)
                random = random.getNext();

            cTemp = current.getItem();
            current.setItem(random.getItem());

            random.setItem(cTemp);
        }
    }
}


和它的工作^ _ ^ 感谢输入。 =)

答案 3 :(得分:0)

我的实现使用分而治之算法对链表进行洗牌

public class LinkedListShuffle
{
    public static DataStructures.Linear.LinkedListNode<T> Shuffle<T>(DataStructures.Linear.LinkedListNode<T> firstNode) where T : IComparable<T>
    {
        if (firstNode == null)
            throw new ArgumentNullException();

        if (firstNode.Next == null)
            return firstNode;

        var middle = GetMiddle(firstNode);
        var rightNode = middle.Next;
        middle.Next = null;

        var mergedResult = ShuffledMerge(Shuffle(firstNode), Shuffle(rightNode));
        return mergedResult;
    }

    private static DataStructures.Linear.LinkedListNode<T> ShuffledMerge<T>(DataStructures.Linear.LinkedListNode<T> leftNode, DataStructures.Linear.LinkedListNode<T> rightNode) where T : IComparable<T>
    {
        var dummyHead = new DataStructures.Linear.LinkedListNode<T>();
        DataStructures.Linear.LinkedListNode<T> curNode = dummyHead;

        var rnd = new Random((int)DateTime.Now.Ticks);
        while (leftNode != null || rightNode != null)
        {
            var rndRes =  rnd.Next(0, 2);
            if (rndRes == 0)
            {
                if (leftNode != null)
                {
                    curNode.Next = leftNode;
                    leftNode = leftNode.Next;
                }
                else
                {
                    curNode.Next = rightNode;
                    rightNode = rightNode.Next;
                }
            }
            else
            {
                if (rightNode != null)
                {
                    curNode.Next = rightNode;
                    rightNode = rightNode.Next;
                }
                else
                {
                    curNode.Next = leftNode;
                    leftNode = leftNode.Next;
                }
            }

            curNode = curNode.Next;                     
        }
        return dummyHead.Next;
    }

    private static DataStructures.Linear.LinkedListNode<T> GetMiddle<T>(DataStructures.Linear.LinkedListNode<T> firstNode) where T : IComparable<T>
    {
        if (firstNode.Next == null)
            return firstNode;

        DataStructures.Linear.LinkedListNode<T> fast, slow;
        fast = slow = firstNode;
        while (fast.Next != null && fast.Next.Next != null)
        {
            slow = slow.Next;
            fast = fast.Next.Next;
        }
        return slow;
    }
}

答案 4 :(得分:0)

刚刚遇到这个并决定发布一个更简洁的解决方案,它允许您指定您想要做多少改组。

出于答案的目的,您有一个包含PlayingCard对象的链接列表;

LinkedList<PlayingCard> deck = new LinkedList<PlayingCard>();

为了洗牌他们使用这样的东西;

public void shuffle(Integer swaps) {    
    for (int i=0; i < swaps; i++) {
        deck.add(deck.remove((int)(Math.random() * deck.size())));
    }                       
}

你做的掉期越多,列表就越随机化。