I'm a newbie and I don't understant clearly about linked list, so when I write my program, I'm in trouble with it . It have a error in ostream& operator<<(ostream& os, const LinkedList &ll)
and I don't figure out. This is my code:
LinkedList.h
#pragma once
#include<iostream>
using namespace std;
struct Node
{
int infor;
Node *pNext;
};
class LinkedList
{
Node *pHead, *pTail;
int curN;
public:
//default constructor
LinkedList();
//destructor
~LinkedList();
static Node* CreateNode(const int& n);
Node* AddHead(const int &n);
Node* AddTail(const int &n);
Node* RemoveHead();
Node* RemoveTail();
friend ostream& operator<<(ostream& os, const LinkedList &ll);
int& operator[](const int& i);
static int SoNguyenMax();
};
LinkedList.cpp
#include "LinkList.h"
LinkedList::LinkedList()
{
pHead = pTail = NULL;
}
LinkedList::~LinkedList()
{
}
static Node* CreateNode(const int &n)
{
Node *NewNode = new Node;
if (NewNode == NULL)
{
cout << "Khong du bo nho" << endl;
return NULL;
}
else
{
NewNode->infor = n;
NewNode->pNext = NULL;
}
return NewNode;
}
Node* LinkedList::AddHead(const int &n)
{
Node *u = new Node;
u->infor = n;
if (pHead == NULL)
pHead = pTail = u;
else
{
u->pNext = pHead;
pHead = u;
}
return pHead;
}
Node* LinkedList::AddTail(const int &n)
{
Node *u = new Node;
u->infor = n;
if (pHead == NULL)
pHead = pTail = u;
else
{
pTail->pNext = u;
pTail = u;
}
return pTail;
}
Node* LinkedList::RemoveHead()
{
Node *p;
p = pHead;
pHead = pHead->pNext;
delete p;
return pHead;
}
Node* LinkedList::RemoveTail()
{
Node *p, *q;
p = pHead;
while (p != pTail)
{
q = p;
p = p->pNext;
}
pTail = q;
q->pNext = NULL;
delete p;
return pTail;
}
ostream& operator<<(ostream& os, const LinkedList &ll)
{
for (Node *k = ll.pHead; k != NULL; k = k->pNext)
os << k->infor << " ";
return os;
}
main function
#include"LinkList.h"
int main()
{
LinkedList l;
l.AddHead(15);
l.AddHead(123456);
cout << l << endl;
return 0;
}
and: [Autos table: ]
- k 0xcdcdcdcd {infor=??? pNext=??? } Node *
- ll.pHead 0x00abf4d8 {infor=123456 pNext=0x00abf238 {infor=15 pNext=0xcdcdcdcd {infor=??? pNext=??? } } } Node * const
- ll{pHead=0x00abf4d8 {infor=123456 pNext=0x00abf238 {infor=15 pNext=0xcdcdcdcd {infor=??? pNext=??? } } } ...}
Please help me. Thanks!