joseph koh joseph koh - 1 year ago 92
Java Question

Doubly Linked List

I am currently working on my assignment on Card game using DoublyLinkedList (DLL) data structure. I want to choose 4 pairs of cards by random from the deck of cards and swap the content of the cards around without switching the nodes. So basically, we just use random generator and randomly assign the index of the card based on the amount of cards left. The problem is how do i assign the index to the cards and swap them around. In arraylist, we simply just use the get and set method. However, for Doubly Linked List (DLL) i recon we need to access the DLL class? Can anyone help?

public void swap() {
int index1, index2;
Card temp;
Random generator = new Random();
for(int i=0;i<4;i++){
index1 = generator.nextInt( cards.getSize() - 1 );
index2 = generator.nextInt( cards.getSize()- 1 );
//swapping codes here which im stuck here

Answer Source

So the structure of your deck is like this; a Deck has a DLL which has nodes which has a card. If you want to swap the cards with out changing the nodes in the DLL you can change your nodes data field.

You already have the index of the cards you want, so now get references to the nodes. Because you're using a list, there really isn't a better way than to implement a linear search. In your DLL class you could make a method like public Node getNode(Int n). In this method, loop to the next node from head n times, and return that node.

Say that node1 and node2 are parameters of type node you found by using the prior method, or something similar. You can swap the T data field of type node. In the deck class you now the type of your DLL is card. So using the getData() and setData() methods, swap the values (you'll have to make a temporary variable to hold one node's data while you swap them).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download