I am moving here from my other post. But this time I am able to obtain some type of output. But I cannot seem to iterate through my nodes and get them to print out individually as how it should look on the output. Here is what I have so far and also a screenshot of what the program should output.
LList.h
#ifndef LList_h
#define LList_h
#include <iostream>
#include "node.h"
class LList
{
public:
LList(void); //constructor
LList(const LList &); //copy constructor
~LList(); //destructor
LList *next; //points to next node
void push_back(const string &str);
void push_front(const string &str);
friend ostream& operator<<(ostream& out, const LList& llist);
LList &operator=(const LList &l);
private:
Node *_head;
Node *_tail;
LList *front; //points to front of the list
};
inline LList::LList(void)
{
cerr << "head = tail = 0 at 0024f8d0\n";
_head = 0;
_tail = 0;
front = 0;
}
inline void LList::push_back(const string &str)
{
Node *p = new Node(str);
if (_tail == 0)
{
_head = _tail = p;
}
else
{
_tail ->next(p);
_tail = p;
}
if (_head == 0)
{
_head = _tail = p;
}
else
{
_head ->next(p);
_head = p;
}
}
inline void LList::push_front(const string &str)
{
Node *p = new Node(str);
if (_tail == 0)
{
_head = _tail = p;
}
else
{
_tail ->next(p);
_tail = p;
}
if (_head == 0)
{
_head = _tail = p;
}
else
{
_head ->next(p);
_head = p;
}
}
LList & LList::operator=(const LList &l)
{
_head = l._head;
_tail = l._tail;
front = l.front;
return *this;
}
inline LList::~LList()
{
}
#endif
maind.cpp
#include "LList.h"
#include <iostream>
using namespace std;
ostream& operator<<(ostream& out, const LList& llist);
int main( )
{
LList a;
a.push_back( "30" );
a.push_front( "20" );
a.push_back( "40" );
a.push_front( "10" );
a.push_back( "50" );
cout << "list a:\n" << a << '\n';
return 0;
}
ostream &operator <<( ostream &out, const LList & llist )
{
for( LList *p = llist.front; p != 0; p = p -> next )
out << p -> next;
return out;
}
out << p -> next;
This line will skip your first element and cause undefined behavior (possibly segfault) on your last element. This should be out<<p
.
Your operator<<
will print nothing because LList::front
is never assigned to. It's always null.
Your push algorithms make no sense. To push something at the back of the list, you only want head
to be modified if the list is empty, but you have:
if (_head == 0)
{
_head = _tail = p;
}
else
{
_head ->next(p);
_head = p;
}
Why are you setting _head
to p
if the list had entries in it already? Your code has a number of similar bugs -- the logic just isn't right.
The end should probably just be:
if (_head == 0)
_head = p;
If there's already a node at the head, adding an entry to the back doesn't affect head at all.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.