파일에서 문자열을 읽어 알파벳 순서 (C++)로 LinkedList에 삽입합니다. 나는 노드와리스트 클래스를 만들었지 만 뭔가 잘못되었다. Java에서이 작업을 수행했으며 문제없이 100 % 작동합니다. 이것은 내가 어딘가에서 포인터를 망쳐 놓았음에 틀림 없다고 믿게한다. 이것은 두 번째로 '->'기호를 사용하는 경우이기도합니다. 그래서 나는 그것을 어딘가에서 잘못 사용했을지도 모른다. 도움이되는 몇 가지 정보를 보내 주시면 감사하겠습니다. 미리 감사드립니다.오류는 없지만 출력이 올바르지 않습니다. 포인터 문제 가능
//NODE CLASS
#include <string>
#include <iostream>
using namespace std;
class Node {
string word;
int count;
Node* next;
public:
Node (string aWord) {
word = aWord;
count = 1;
}
Node (string aWord, Node* theNext) {
word = aWord;
next = theNext;
}
void increaseCount() {
count++;
}
string getWord() {
return word;
}
int getCount() {
return count;
}
Node* getNext() {
return next;
}
void setNext(Node* theNext) {
next = theNext;
}
};
//LIST CLASS
#include<iostream>
using namespace std;
class LinkedList {
Node* head;
public:
LinkedList() {
head = new Node(" ");
}
void insert(string word) {
Node* temp = head;
Node* previous = head;
while (temp != NULL && temp->getWord() < word) {
previous = temp;
temp = temp->getNext();
}
if (temp == NULL) {
Node* node= new Node(word);
previous-> setNext(node);
} else {
if (temp-> getWord() == word) {
temp->increaseCount();
} else if (temp->getWord() > word) {
Node* node = new Node(word, temp);
previous->setNext(node);
}
}
}
void print() {
Node* temp = head->getNext();
while (temp != NULL) {
cout<< temp;
temp=temp->getNext();
}
}
};
//MAIN
#include <iostream>
#include <iostream>
#include <fstream>
#include "Node.h"
#include "LinkedList.h"
using namespace std;
int main(int argc, const char * argv[]) {
ifstream inFile("WordsStatisticData1.txt");
if (!inFile.is_open())
cout<< "Could not open the file"<< endl;
else {
string readData;
LinkedList list = *new LinkedList(); //Probably a problem here
while (inFile >> readData) {
list.insert(readData);
inFile.close();
list.print();
}
}
}
본인도 메인 내에서 완전히 잘못 선언 할 수 있습니다. 내 출력이 임의 문자가있는 '0x'주소와 비슷합니다.
'LinkedList list = * new LinkedList();는 메모리 누수입니다. 어떻게 그걸 풀어 주죠? 사실, 나는 여기에 포인터가 전혀 필요 없다고 생각합니다. –
참. 내 잘못이야. 이 부분에 대한 할당이 필요 없습니다. – Sgacedas
@ DSib13 -'나는 Java에서이 작업을 수행했으며 문제없이 100 % 작동합니다. 'Java는 가비지 수집의 형태로 모든 동적 메모리 관리를 수행하기 때문에. 사실, 당신의 코드는'delete'에 대한 호출이 없기 때문에 메모리가 새어 나올 수 있습니다. 자바에서는 그다지 걱정하지 않아도됩니다. – PaulMcKenzie