我试图创建一个简单的双链接列表,以熟悉c++中的指针。每个节点包含一个整数、一个指向下一个节点的指针和一个指向前一个节点的指针。当我试图输出链接列表对象中每个节点的值时,它将无限期地打印值。
我的测试代码用一个节点初始化一个链接列表,并添加另外3个节点。
当调用PrintNodeVals()方法时,while循环无限期地迭代,输出节点值的常量流。当使用for循环而不是while循环时,它只打印一次头节点的地址,然后继续打印第二个地址,这是使用addnode()方法附加的第一个节点,也是链接列表中的第二个节点。
我能想到的唯一解释是,我的代码以某种方式将第二个节点指定为指向节点本身的“下一步”指针,这将导致PrintNodeVals() while循环始终计算为true。
有什么想法吗?
#include "LinkedList.h"
LinkedList::LinkedList(){
root = new Node();
}
//adds node to the end of the list
void LinkedList::addnode(){
Node newnode;
Node *conductor = root;
while(conductor->next != 0){
conductor = conductor->next; //(*conductor).next
}
conductor->next = &newnode; //makes the next field point to the new node
newnode.prev = conductor;
}
void LinkedList::PrintNodeVals(){
Node *conductor = root;
while(conductor != 0){
std::cout << conductor->val;
conductor = conductor->next;
}
/*
for(int i = 0; i < 10; i++){
std::cout << conductor << "\n";
conductor = conductor->next;
*/
}
}
//TEST CODE
#include <iostream>
#include "LinkedList.h"
using namespace std;
int main()
{
LinkedList linkle;
linkle.addnode();
linkle.addnode();
linkle.addnode();
linkle.ShowNodeVals();
return 0;
}发布于 2015-11-20 06:15:50
问题是在列表中存储指向局部变量的指针:
Node newnode;
// ...
conductor->next = &newnode;newnode在块的末尾被销毁,指针变得无效。您可能应该动态分配新节点,或者使用std::list而不是您自己的list类。
https://stackoverflow.com/questions/33820102
复制相似问题