這是我在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