【发布时间】:2011-02-05 07:00:48
【问题描述】:
//element of chain.
struct studentRecord
{
int score;
string* name;
int operator !=(studentRecord x) const
{return (score != x.score);}
};
// binsort, theChain is a single linked list of students and its element is student Record
void binSort(chain<studentRecord>& theChain, int range)
{// Sort by score.
// initialize the bins
chain<studentRecord> *bin;
bin = new chain<studentRecord> [range + 1];
// distribute student records from theChain to bins
int numberOfElements = theChain.size();
for (int i = 1; i <= numberOfElements; i++)
{
studentRecord x = theChain.get(0);
theChain.erase(0);
bin[x.score].insert(0,x);
}
// collect elements from bins
for (int j = range; j >= 0; j--)
while (!bin[j].empty())
{
studentRecord x = bin[j].get(0);
bin[j].erase(0); ////////// here
theChain.insert(0,x);
}
delete [] bin;
}
chain<studentRecord>是一个单链表;在 bin 排序中, bin 是指向 bin[arrange +1] 的指针,其元素为 chain<studentRecord> 。代码bin[j].erase(i) 将delete 节点i。 bin[j].get(i) 将获取节点 i 的元素(即 studentRecord)。代码中while (!bin[j].empty())是用来清空链的,但是bin[j]不能为空,因为它是一个元素数组,对吗?
谢谢。
【问题讨论】: