By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
454,596 Members | 1,869 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 454,596 IT Pros & Developers. It's quick & easy.

SHuffling a Linked List

P: n/a
Hi,

Trying to shuffle a linked list of cards around. I know not the ideal
structure to use, but it is what my professor wants. I wrote all the
code and the logic makes sense, but for some reason when my random
integer is 0, it links the current node to itself and just breaks the
entire linked list.

Thanks for any help,

Rishi

void shuffle()
{

node<card*curr = NULL, *prev = NULL;

int myIndex;

randomNumber rnd;

// move 50 cards around
for (int i = 0; i < 50; i++)
{
long rndNum = rnd.random(52);

myIndex = 0;

curr = front;

// scan until index reaches rndNum or reach end of list
while (curr != NULL && myIndex != rndNum)
{
prev = curr;
curr = curr->next;
myIndex++;
}

// if prev == null, that means we are shuffling first node so just
dont do anything
if (prev != NULL)
{
cout << myIndex << " - curr " << curr->nodeValue.getValue() << "
prev " << prev->nodeValue.getValue() << endl;
prev->next = curr->next;
curr->next = front;
front = curr;
}
}
}

Nov 15 '06 #1
Share this Question
Share on Google+
1 Reply


P: n/a
RishiD wrote:
Hi,

Trying to shuffle a linked list of cards around. I know not the ideal
structure to use, but it is what my professor wants. I wrote all the
code and the logic makes sense, but for some reason when my random
integer is 0, it links the current node to itself and just breaks the
entire linked list.

Thanks for any help,

Rishi

void shuffle()
{

node<card*curr = NULL, *prev = NULL;
You initialize prev once, up here, and then...
>
int myIndex;

randomNumber rnd;

// move 50 cards around
for (int i = 0; i < 50; i++)
{
long rndNum = rnd.random(52);

myIndex = 0;

curr = front;

// scan until index reaches rndNum or reach end of list
while (curr != NULL && myIndex != rndNum)
{
prev = curr;
curr = curr->next;
myIndex++;
}

// if prev == null, that means we are shuffling first node so just
dont do anything
.... you check it down here, when it may not have been reinitialized.
Think: what is the state of prev in the case where rndNum = 0?
if (prev != NULL)
{
cout << myIndex << " - curr " << curr->nodeValue.getValue() << "
prev " << prev->nodeValue.getValue() << endl;
prev->next = curr->next;
curr->next = front;
front = curr;
}
}
}
Nov 15 '06 #2

This discussion thread is closed

Replies have been disabled for this discussion.