1

我创建了 2 个名为 nodelist.h 和 nodelist.cpp 的文件,其中的函数基本上包含基本的链表函数,例如(例如 addNode、printNode...等)。之后我创建了另一个源文件来利用在该类中创建的函数如下所示:

#include "NodeList.h"

bool insertR(stringstream &lineStream)
{

    int node1,node2;
    lineStream>> node1 >> node2;
    nodelist *n1 = new nodelist; //EDIT: FIXED
    nodelist *n2 = new nodelist; // EDIT: FIXED
    n1->addNode(node1);
    n2->addNode(node2);
    n1->print();
    n2->print();
    return true;
}

请注意,此函数不在 main 中,它是 main 调用的另一个源文件。我的 nodelist.cpp 工作正常,虽然这个程序运行,但当我输入节点值时,我的程序崩溃了。有什么帮助吗?

这是我的节点列表文件:

#include <iostream>

#include "NodeList.h"

using namespace std;

nodelist::nodelist(){
                 head = NULL;
                 current = NULL;
                 temp = NULL;
}

void nodelist::addNode(int node_id_){
 nodePtr n = new Node;
 n->next = NULL;
 n->node_id = node_id_;
 if(head!=NULL)
 {
     current = head;
     while(current->next != NULL)
     {
         current = current ->next;                    
     }
     current->next = n;                    
 }
 else
 {
     head = n;    
 }
}

void nodelist::deleteNode(int del_node){
 nodePtr delPtr = NULL;
 temp = head;
 current = head;
 while(current!=NULL&&current->node_id!=del_node){
     temp = current;
     current = current->next;
     }
 if (current == NULL)
     {
         cout << del_node<<" does not exist"<<endl;   
         delete delPtr;         
     }
 else
     {
         delPtr = current;
         current  = current->next;
         temp->next= current;
         delete delPtr;
         cout << del_node<< " has been deleted"<<endl;      
     }
  }


 void nodelist::print(){
 current = head;
 while(current != NULL){
     cout << current->node_id<<endl;
     current = current ->next;       
 }

}

编辑:所以现在当我创建一个节点列表类型的新对象时它可以工作,但是当我传入 node1 和 node2 的值时,我得到一个不对应于任何一个节点的连续循环。但是,如果我在 main() 中执行此操作,则此方法有效。

4

2 回答 2

2
nodelist *n1; // unintialized pointer
nodelist *n2; // another uninitialized pointer
n1->addNode(node1); // you try to use an uninitialized pointer
n2->addNode(node2); // same here
n1->print(); // and here
n2->print(); // and here!

如果不了解您是如何声明/实现链表类的,就很难为您的整体问题提供潜在的解决方案。但是崩溃是由您尝试访问随机内存块并将它们视为nodelist对象(例如未定义的行为)引起的。

于 2013-11-01T00:00:36.477 回答
2

仅声明指针是不够的,您需要使用 new 运算符来实例化它们指向的节点列表。

n1 和 n2 没有指向任何东西,这就是它崩溃的原因

nodelist *n1;
nodelist *n2;
n1->addNode(node1);
n2->addNode(node2);
于 2013-10-31T23:57:23.050 回答