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;
}
代码中也存在一个错误,当条件为真时,在 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
相关文章:
- 从链接列表c++中删除一个项目
- 读取文件的最后一行并输入到链接列表时出错
- 下面是我为检测链接列表中的循环而制作的代码
- 有人能帮我处理这个链接列表吗?C++
- C++ 创建包含链表和字符串的对象的链接列表时出错
- 你能检查一下为什么在这个代码中从链接列表中删除项目不起作用吗
- 为什么它只打印双链接列表的第一个值,而我的程序却崩溃了
- 链接列表运算符重载没有打印出我想要的内容
- 链接列表在 cpp 中包含不同的对象类
- 创建一个棋盘格或"Interweave"两个链接列表。IE 更改两个链表的指针
- 如何在构建链接列表时调整头、尾指针
- Shared_ptr双链接列表内存泄漏
- 为什么每当我尝试运行此链接列表删除功能时都会收到分段错误错误?
- 在链接列表中查找元素 - C++
- 删除链接列表中剩余的最后一个节点
- 只有我的"链接列表"中的第一个节点正在打印
- 避免在使用链接列表从 deque 中删除最后一个节点时出现内存泄漏
- C++ 分段错误:11 错误,同时编码将两个数字相加的链接列表
- 如何在C / C++中正确实现链接列表而不会使程序崩溃
- 将元素插入链接列表