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

C++ Linked List that mimics vectors

本文关键字:链接 列表 向量 C++      更新时间:2023-10-16

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

代码中也存在一个错误,当条件为真时,在 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没有实际意义,除非位置为零。它目前适用于您到目前为止运行的数字和案例。它不适用于所有情况.....

编辑----

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