Shuffling elements in a linked list.
I'm trying to shuffle elements in a linked list without using another linked list or array. I'm supposed to manipulate the linked list directly. I'm completely stumped as to how I'd go about doing this. In my node class I only have 4 methods ( setItem(), setNext(), getNext(), and getItem() )
Some guidance would be appreciated =)
Re: Shuffling elements in a linked list.
Well, if this is the Deck program again, unless you changed it I don't believe you are using the LinkedList API, I am no pro but as I understand it, you made a "linked list" of your node classes, but without utilizing the API...if that makes sense. I did a quick search of linkedlist and it would appear you should initialize the list myDeck = new LinkedList(); and then add the nodes and then use get() and set() perhaps...but then what is the point of the Nodes, if you could explain whats going on a little better it would help I think.
You can move an element in your Node list to the front(Like the way a kid shuffles) with:
Code :
int RANDOM_NUMBER = (int) ((Math.random()*52));
Node traveller = front;
for(int i = 0;i<RANDOM_NUMBER;i++ ) {
traveller = traveller.getNext();
}
Node second = front;
if(traveller.getNext() != null) front = traveller.getNext();
traveller.setNext(front.getNext());
front.setNext(second);
Do that a random or specified amount of times and it should shuffle your deck.