该程序基本上只是假设可以随机播放一副纸牌。这些卡存储在一个双向链表中,因此有52个节点。我在getNode函数中遇到读取访问错误,但是我可以肯定我的循环是正确的,因此我认为该错误是由其他地方引起的。也许交换功能。我的第一步是获取指向我要交换的节点的指针。
所以我做了一个函数,我确定它是对的,只是我想知道是否应该返回* traverseP而不是traverseP。我不这么认为,因为我想返回一个指向该节点的指针,而不是该节点内部的值。
template<class T>
typename ReorderableList<T>::Node *ReorderableList<T>::getNode(int i) const
{
int count = 0;
for (Node *traverseP = firstP; traverseP != NULL; traverseP = traverseP->nextP) {
if (count == i)
return traverseP;
count++;
}
return NULL;
}
接下来,我制作了一个交换函数,它带有两个整数,它们表示我传递给getNode函数的值
template<class T>
void ReorderableList<T>::swap(int i, int j)
{
// Get pointers to ith and jth nodes.
Node *iPtr = getNode(i);
Node *jPtr = getNode(j);
//create temp Node and store the pointers
Node *temp = new Node;
temp = iPtr->prevP;
temp = iPtr->nextP;
//adjust the iPtr next/prev pointers
iPtr->prevP = jPtr->prevP;
iPtr->nextP = jPtr->nextP;
//adjust the jPtr next/prev pointers
jPtr->prevP = temp->prevP;
jPtr->nextP = temp->prevP;
//I'm a little unclear on these lines. I think they're checking if
//iPtr and jPtr have null pointers. I've tried making them equal jPtr and
//iPtr and that strangly didn't make any difference.
if (iPtr->prevP)
iPtr->prevP->nextP = jPtr;
if (iPtr->nextP)
iPtr->nextP->prevP = jPtr;
if (jPtr->prevP)
jPtr->prevP->nextP = iPtr;
if (jPtr->nextP)
jPtr->nextP->prevP = iPtr;
delete temp;
}
这是整个沙邦开始的随机播放功能
template<class T>
void randomShuffle(ReorderableList<T> &list, int n)
{
int randNum = 0;
for (int i = n-1; i > 0; i--)
{
randNum = (rand() & (i + 1));
if (randNum > i)
std::swap(randNum, i);
list.swap(randNum, i);
}
}
我检查了交换功能的几个不同资源,发现其中两个都声称它们是正确的,但对我来说看起来却不一样。 Resource 1 Resource 2