You are using a version without Ads of this website. Please, consider donating:

I had to create a list class and add a "<<" function.
this is the code I wrote:
 ``123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153`` `````` template class Node { private: T val; Node * next; public: Node (const T & x) { val = x; next = 0; } void setVal (const T& x) { val = x; } T getVal () { return val; } void setNext (Node * x) { next = x; } Node * getNext () { return next;} }; template class List { private: Node * n; int size; public: List () { n = 0, size = 0; } Node * add (Node * pos,const T & x) { Node * temp = new Node (x); if (size == 0) { n = temp; pos = n; } else { if (pos == 0 && size!= 0) { temp -> setNext(n); n = temp; pos = n; } else { Node * p = n; while ( p != pos) p = p -> getNext(); p -> setNext(temp); pos = p -> getNext(); } } ++size; return pos; } Node * remove (Node * pos) { if (pos == n && size == 1) { --size; n = 0; return 0; } int counter = 1; Node * p = n; while ( (p -> getNext()) != pos) { ++counter; p = p -> getNext(); } if (pos -> getNext() == 0) p -> setNext(0); p -> setNext ( pos ->getNext() ); --size; return p -> getNext(); } Node * search (Node * pos) { Node * p = n; while ( p != pos ) { p = p -> getNext(); } return p; } int getSize () { return size; } template friend ostream& operator<< (std :: ostream& , const List& ); }; template ostream& operator << (std:: ostream& os, const List & lst) { os << "[" << lst.n -> getVal(); Node * p = lst.n -> getNext (); for (int i = 1; i < lst.size; ++i) { os << " , " << p ->getVal(); p = p -> getNext(); } os << "]"; return os; } int main () { Node * a; Node * b; List * lst = new List (); a = lst -> add(0,'a'); a = lst -> add (a, 'b'); b = a; a = lst -> add (a, 'D'); a = lst -> remove (b); cout << a -> getVal() << endl; cout << lst; return 0; }``````

the last line (cout << lst) prints a random number (I think it's the os address..?). can anyone tell me what's wrong with it?
`lst` is a pointer. So you're printing the contents of a pointer, which is naturally an address.

You are overusing pointers in my opinion. You also have a memory leak because you must pair each new with a delete.

So you must dereference the pointer by using the asterisk operator, and also `delete lst;` in the end.

 ``12345678910111213141516`` ``````int main () { Node *a; Node *b; List *lst = new List(); a = lst->add(0,'a'); a = lst->add(a, 'b'); b = a; a = lst->add(a, 'D'); a = lst->remove(b); cout << a->getVal() << endl; cout << *lst; delete lst; return 0; }``````

Also I would suggest you compact your code a little.
Last edited on
thanks!
Topic archived. No new replies allowed.