I have a problem either adding to or traversing a linked list. The main item class is used by another class but I can add the correct number of these but it looks like when I add more data to the list the app no longer works.
I am not sure exactly where the error is. I know that when I try to traverse the list the application crashes. Any ideas or any improvements would be appreciated.
I can make the crash not happen by changing the AddOccurence method to not do the while loop.
Do
void Item::AddOccurence(int Item,int placeInLine){
ItemOccurence* ocr=myHead;
if(ocr)
{
}
instead of
void Item::AddOccurence(int Item,int placeInLine){
ItemOccurence* ocr=myHead;
while(ocr)
{
}
Basically hitting the first node but no more.
I have an object that contains a list. Here is the .h file #include using namespace std;
class ItemOccurence{
public:
ItemOccurence(int line,int placeInLine,ItemOccurence* link=NULL) :myLine(line),myPlaceInLine(placeInLine),myLink(link){}
int myLine;
int myPlaceInLine;
ItemOccurence* myLink;
};
class Item {
public:
Item();
Item(string Item,int line,int placeInLine);
virtual ~Item();
void deallocate(ItemOccurence* p);
void AddOccurence(int Item,int placeInLine);
string myItem;
ItemOccurence* myHead;
private:
bool isEmpty();
};
And the .cpp file
#include "Item.h"
#include <string>
#include<iostream>
using namespace std;
Item::Item(string Item,int line,int placeInLine):myHead(NULL){
myItem=Item;
myHead= new ItemOccurence(line,placeInLine,NULL);
}
Item::Item():myHead(NULL){
myHead=0;
}
Item::~Item() {
deallocate(myHead);
myHead=0;
}
void Item::deallocate(ItemOccurence* p){
ItemOccurence* tmp;
while(p){
tmp=p;
p=p->myLink;
delete tmp;
}
}
void Item::AddOccurence(int Item,int placeInLine){
ItemOccurence* ocr=myHead;
while(ocr)
{
cout<<"orrucence head while adding " << myHead->myLine << " " << myHead->myPlaceInLine <<"\n";
ocr=ocr->myLink;
}
myHead = new ItemOccurence(Item,placeInLine,myHead);
return;
}
bool Item::isEmpty(){
if(myHead)
return false;
else
return true;
}
EDIT: I updated AddOccurence to be.
void Item::AddOccurence(int line,int placeInLine){
ItemOccurence* prev = myHead;
ItemOccurence* curr = myHead->myLink;
while(curr){
prev=curr;
curr=curr->myLink;
}
// insert new ItemOccurence
cout<<"adding " <<line<< " and " << placeInLine <<"\n";
prev->myLink = new ItemOccurence(line,placeInLine);
return;
}
But I am still crashing. I am trying to debug but not sure what to look for.