0

我想知道这段代码是否正确地模仿了使用链表的向量的“at”函数。这个概念是为了教我们链表,我不确定我是否将 pos++ 放在正确的位置。有人可以帮助我并告诉我每行在做什么,以便我知道它是如何退出 while 循环的吗?到现在为止,很混乱。谢谢你!

这是整个项目的pastebin:http: //pastebin.com/wyNQx3GP

多谢你们

 // This returns the countyElectionResults result at a particular point
 // in the list.
 // This is analogous to the at method in the vector class.
 countyElectionResults countyElectionList::at(int place){
    if(head == NULL){
            countyElectionResults * name = NULL;
            return * name;
    }
    else{
            countyElectionResults * current = head;
            int pos = 0;
            while(pos != place && current->getNextResult() != NULL){
                    current = current->getNextResult();
            }
            pos++;
            return * current;
    }
    cout << "Not Found" << endl;
 }
4

3 回答 3

1

代码中还有一个错误,在 if 条件为 true 时的 return 语句处:

countyElectionResults countyElectionList::at(int place){
    if(head == NULL){
            // if head is null, then set name to NULL
            countyElectionResults * name = NULL;
            // This is segmentation fault due to dereferencing name (null)
            return * name;
    }
    else{
            // set the current to list head and pos to 0
            countyElectionResults * current = head;
            int pos = 0;
            // compare pos to place, while these are different
            // and list does not end
            while(pos != place && current->getNextResult() != NULL){
                    // set current to next node
                    current = current->getNextResult();
            }
            pos++;  // this should be inside the loop, incremented when current 
                    // advances
            return * current; 
    }
    cout << "Not Found" << endl;
 }
于 2012-12-17T11:33:27.513 回答
0

不,pos++ 应该在 while 循环内。

while(pos != place && current->getNextResult() != NULL)
{
   当前 = 当前->getNextResult();
   正++;
};
于 2012-12-17T11:28:06.180 回答
0

pos++ 应该在循环内,因为您必须计算循环时通过的位置。如果你不这样做,那么检查pos != place没有实际意义,除非 place 为零。它目前适用于您迄今为止运行的数字和案例。它不适用于所有情况......

编辑 - -

当我说不起作用时,我的意思是它会给出错误的结果,而不是它不会编译或给出一个 SIGSEV

于 2012-12-17T11:31:01.567 回答