这是我在StackOverflow上的第一篇文章,因为我真的被卡住了。 我的问题是,每次运行下面的代码时,首次调用函数InsertNode()时,返回临时节点对于下一个节点和数据都具有正确的值。但是,当函数再次被调用时,由于某些原因,头部被重置为数据NULL,并且下一个指针递归地指向相同的地址。我很难在OOP中实现这一点,我已经成功地使用了简单的结构来完成这个任务。但是对于OOP,我很困惑如何声明Node * Node :: InsertNode(Node * head),方法在main中,因为我得到一个InsertNode未声明的错误。因此,作为解决方法,我将InsertNode作为独立函数声明在Node类之外。我有一种感觉,那就是可能导致问题的原因。将不胜感激一些帮助正在发生什么或我应该改变我的代码。谢谢!C++链接列表使用类(OOP)
hashtable.cpp
#include "Hashtable.hpp"
using namespace std;
Node::Node(){
data = NULL;
Node* nextP = NULL;
};
Node::~Node(){
}
Node* InsertNode(Node* head, int data){
Node* temp = new Node();
if(head->nextP == NULL){
head->data = data;
temp->nextP = head;
head = temp;
} else if(head->nextP!=NULL){
temp->nextP = head;
temp->data = data;
head = temp;
}
return head;
};
void Node::printNode(Node* head){
Node* temp = new Node();
temp = head;
while(temp->nextP != NULL){
printf("%d\n", temp->data);
temp = temp->nextP;
}
}
Hashtable.hpp
#ifndef Hashtable_hpp
#define Hashtable_hpp
#include <stdio.h>
class Node
{
public:
Node* nextP;
Node();
~Node();
void printNode(Node* head);
int data = NULL;
private:
};
Node* InsertNode(Node* head, int data);
#endif /* Hashtable_hpp */
的main.cpp
#include <iostream>
#include "stdio.h"
#include <string>
#include "Hashtable.hpp"
using namespace std;
Node head;
//Node* head = new Node();
int main(int argc, const char * argv[]) {
// insert code here...
std::cout << "Hello, World!\n";
head = *InsertNode (&head, 10);
// head = temp2;
head = *InsertNode (&head, 20);
// head = temp2;
head = *InsertNode (&head, 30);
// head = temp2;
//InsertNode(head, 20);
Node printNode(head);
return 0;
}
吨。其中一位可能会告诉你这是错误的。 – user4581301
你的错误似乎很明显。这是一个学习如何使用调试器的绝佳机会,以便一次检查一行代码,同时检查所有变量和对象的值,以便自己弄清楚。下一次你发现自己处于这种状况时,你可以自己弄明白,而不需要在stackoverflow.com上寻求帮助。了解如何使用调试器是每个C++开发人员必备的技能。 –
谢谢。我在当前的每一行设置了断点,并能够在第一次运行时看到正确设置的值。但在第二次运行时,头部会重新设置为空。我意识到我的逻辑可能是错误的功能。但是我想了解是否在类的外部声明InserNode函数与头节点重置有关。 void类型方法(PrintNode)在类中声明时不引发错误,但是如果我以同样的方式声明InsertNode方法:Node * Node :: InsertNode(Node * head,int data);我收到一个错误,说它是未定义的。 – sr2002