I’m having a very hard time using a pseudo code for the shuffling algorithm and turning it to a working java code. I’m attempting to shuffle a linked list. Overall the method takes the pointer of the head of the linked list and returns a pointer to the head of the same list randomly. I want to use a getLength and getItem method I’ve created.
public static ListElement shuffle(ListElement head){
head = head.getLength();
ListElement head2= null;
while( head == null) {
int random = (int) Math.random() * n;
for(int i=0;i<random;i++){
head= head.getNext();
}
}
return head;
}
Pseudo code:
A list L of length n
A new list R, empty
while L is not empty
pick a random k
such that 0<=k<= (length L)
remove the kth element of L
call it e
prepend e to R
I just rewrite the code a bit so that it follows the pseudo code.