For a project, im trying to set up a linked list object so that it can be initialized with an explicit value constructor. I want it to look like this:
WORD you("you");//where the object you's linked list now contains y o u;
but when I print out the object you, all i see is this symbol "=" and when I print out the length of you, I get -858993459
Here is my explicit value constructor, can someone tell me what I am doing wrong?
WORD::WORD(string s)
{
front = 0;
int i = 0;
int len = s.length();
if(front == 0)
{
front = new alpha_numeric;
alpha_numeric *p = front;
while(s[i] <= len)
{
p -> symbol = s[i];
p -> next = new alpha_numeric;
p = p -> next;
p -> symbol = s[i++];
}
p -> next = 0;
}
}
Here is the class declaration file if it helps
#include <iostream>
#include <string>
using namespace std;
#pragma once
class alpha_numeric //node
{
public:
char symbol; //data in node
alpha_numeric *next;//points to next node
};
class WORD
{
public:
WORD(); //front of list initially set to Null
WORD(const WORD& other);
WORD(string s); //***EXPLICIT VALUE CONSTRUCTOR
bool IsEmpty(); //done
int Length();
void Add(char); //done
//void Insert(WORD bword, int position);
//void operator=(char *s);
friend ostream & operator<<(ostream & out, const WORD& w);//done
private:
alpha_numeric *front; //points to the front node of a list
int length;
};
You never set length, so that's why it's garbage. As luthien256 ahd LihO pointed out, your while loop is also wrong, and the if (front == 0) test makes no sense.
Finally, the p -> symbol = s[i++];
is not needed. Just increment i.
Try this:
class alpha_numeric //node
{
public:
char symbol; //data in node
alpha_numeric *next;//points to next node
};
class WORD
{
public:
WORD(); //front of list initially set to Null
WORD(const WORD& other);
WORD(string s); //***EXPLICIT VALUE CONSTRUCTOR
bool IsEmpty(); //done
int Length() { return length; }
alpha_numeric *Front() { return front; }
void Add(char); //done
//void Insert(WORD bword, int position);
//void operator=(char *s);
friend ostream & operator<<(ostream & out, const WORD& w);//done
private:
alpha_numeric *front; //points to the front node of a list
int length;
};
WORD::WORD(string s)
{
front = 0;
int i = 0;
int len = s.length();
length = len;
if (length == 0) {
front = NULL;
return;
}
front = new alpha_numeric;
alpha_numeric *p = front;
while(i < len)
{
p -> symbol = s[i];
if (i != len - 1) {
p -> next = new alpha_numeric;
p = p -> next;
}
else
p -> next = NULL;
++i;
}
}
int main() {
WORD you("you");
alpha_numeric* front = you.Front();
while(front != NULL) {
cout<<(front->symbol)<<endl;
front = front->next;
}
cout<<you.Length()<<endl;
return 0;
}