【发布时间】:2017-03-05 21:08:33
【问题描述】:
这是我在 StackOverflow 上的第一篇文章,因为我真的被困住了。 我的问题是,每次我运行以下代码时,在第一次调用函数 InsertNode() 时,返回的临时节点具有下一个节点和数据的正确值。但是,当再次调用该函数时,由于某些原因,head 被重置为 data NULL,并且 next 指针递归地指向相同的地址。我很难在 OOP 中实现这一点,我已经成功地使用普通结构完成了这一点。但是对于 OOP,我对如何在 main 中声明 Node* Node::InsertNode(Node* head), 方法感到困惑,因为我收到一个错误,即 InsertNode 未声明。因此,作为解决方法,我在 Node 类之外将 InsertNode 声明为独立函数。我有一种感觉,这可能是导致问题的原因。希望对正在发生的事情或我应该在代码中更改的内容提供一些帮助。谢谢!
哈希表.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;
}
}
哈希表.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;
}
【问题讨论】:
-
大量编译器警告。其中一位可能会告诉你这是错误的。
-
您的错误似乎相当明显。这是您学习如何使用调试器的绝佳机会,以便一次单步执行您的代码,同时检查所有变量和对象的值,以便自己弄清楚。下次您发现自己处于这种情况时,您将能够自己解决所有问题,而无需在 stackoverflow.com 上寻求帮助。了解如何使用调试器是每个 C++ 开发人员必备的技能。
-
谢谢。我目前在每一行都设置了断点,并且能够在第一次运行时看到正确设置的值。但在第二次运行时,head 再次重置为 Null。我意识到我的逻辑可能在功能上是错误的。但我试图了解在类之外声明 InserNode 函数是否与重置头节点有关。 void 类型方法(PrintNode)在类中声明时不会抛出错误,但如果我以相同的方式声明 InsertNode 方法: Node* Node::InsertNode(Node* head, int data);我收到一个错误,它是未定义的。
-
“我很困惑如何声明 Node* Node::InsertNode(Node* head), method” 直接的答案是“首先在类中声明函数,然后实现它。”正确答案是“你不想。你想定义和实现一个链表类,并将插入函数放在链表类中。”
标签: c++ oop data-structures linked-list