我是新手,我不清楚链接列表,所以当我编写程序时,我遇到了麻烦。它在ostream& operator<<(ostream& os, const LinkedList &ll)
中有错误,我不知道。这是我的代码:
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;
}
主要功能
#include"LinkList.h"
int main()
{
LinkedList l;
l.AddHead(15);
l.AddHead(123456);
cout << l << endl;
return 0;
}
和: [汽车表:]
请帮帮我。谢谢!
答案 0 :(得分:0)
尝试使用while循环:
ostream& operator << (ostream &os, const LinkedList &ll)
{
Node* k = ll.pHead;
while (k != NULL)
{
os << k->_data << ", ";
k = k->pNext;
}
return os;
}
但我找到了一些东西。 &#34; INFOR&#34;变量可以与&#34; INFO&#34;。
混淆