繁体   English   中英

模仿向量的C ++链表

[英]C++ Linked List that mimics vectors

我想知道这段代码是否正确地模仿了使用链表的向量的“ at”功能。 这个概念是要教我们链表,我不确定是否将pos ++放在正确的位置。 有人可以帮我一下,告诉我每一行在做什么,以便我知道它如何使它退出while循环吗? 截至目前,这令人困惑。 谢谢!

这是整个项目的粘贴框: 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;
 }

如果条件为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;
 }

否。pos++应该在while循环内。

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

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

编辑 - -

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM