模仿向量的C ++链接列表

时间:2012-12-17 11:26:04

标签: c++ linked-list

我想知道这段代码是否使用链表正确地模仿了矢量的“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;
 }

3 个答案:

答案 0 :(得分:1)

如果条件为真,则在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;
 }

答案 1 :(得分:0)

没有。 pos ++应该在while循环中。

while(pos != place && current->getNextResult() != NULL)
{
   current = current->getNextResult();
   pos++;
};

答案 2 :(得分:0)

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

EDIT ----

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