Problem with custom linked list using strings.
Sep 23, 2013 at 11:17pm UTC
Hi, I have an assignment to create a custom linked list class to store strings, but I'm having some issues.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
struct node {
node(string current) { data=current; next=NULL; }
string data;
node *next;
};
class list {
public :
list(int N=0, string current);
~list();
bool empty() const { return N == 0; }
void clear();
void insert(int , const string &);
void push_front(const string ¤t);
friend ostream & operator <<(ostream &out, const list ¤t);
private :
int N;
node *head;
node *findnode(int );
};
list::list(int M, string current) {
N = M;
head = new node;
for (int i=0; i<N; i++)
insert(0, current);
}
list::~list() {
clear();
delete head;
}
void list::clear() {
while (!empty()) remove(0);
}
void list::insert(int i, const string &din) {
node *p = new node(din);
node *pp = findnode(i-1);
p->next = pp->next;
pp->next = p;
N++;
}
inline
node *list::findnode(int i) {
if (i == -1)
return head;
node *p = head->next;
while (i--)
p = p->next;
return p;
}
void list::push_front(const string ¤t) {
head = new node;
head->next;
}
ostream& operator <<(ostream& out, const list& current)
{
out << current;
return out;
}
I'm getting
"terminate called after throwing an instance of 'std::logic_error'
what(): basic_string::_S_construct null not valid"
Which I think is because a string is set to null, I think it would probably be in line 2, but I'm unsure, and unsure how to fix it.
(background: we were given a single linked list program to edit to accept strings for another use).
Sep 24, 2013 at 3:07am UTC
line 9
list(int N=0, string current);
change to
list(int M, string current);
line 31 and 32
1 2
list::list(int M, string current) {
N = M;
The declaration of your constructor on line 9 does not match with this. You can't have an N variable in the class and and pass in an N variable to the constructor.
Line 33
you are using the default constructor here, you don't have one defined.
is this what you want?
head = new node("overloaded constructor" );
Topic archived. No new replies allowed.