gpt4 book ai didi

c++ - 在链表中重载 << 运算符

转载 作者:行者123 更新时间:2023-11-28 07:46:01 25 4
gpt4 key购买 nike

我无法为此创建重载编码。不太确定从哪里开始或什至如何开始。我是 c++ 的新手,即使在阅读了这篇文章之后,也无法理解链表和节点。这是我目前所拥有的。

#include "LList.h"
#include <iostream>

using namespace std;

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 )
{
LList :: //not sure what to really put from here

return out;
}

这是截图 enter image description here

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 &);

private:
Node *_head;
Node *_tail;
LList *front; //points to front of the list

};

inline LList::LList(void)
{
cerr << "default constructor";
}

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;
}

}

inline LList::~LList( )
{
Node *p = new Node (str);

if ( _head == 0)
{
_head = p;
}
else
{
Node *q;
//&Node::next;
for (q = _head; q->next(); q = q -> next)
{
//loop until we have
//q pointing to the last node
}
q->next ( p); //last node points to p
} //_uead still points to the first node

}

#endif

我不太确定我在这方面的进展如何。我只是尝试一些事情并从我教授的一些例子中获得一些想法

最佳答案

你基本上只是<<您想要在重载中打印的元素。例如,假设您有一个 LList::front()返回第一个元素的成员函数,你可以这样打印:

ostream &operator <<( ostream &out, const LList& llist ) {
return out << llist.front();
}

很明显,您希望打印整个列表,而不仅仅是第一个元素(并检查列表是否为空),但方法相同。这假设您的 LList 存储的元素存在过载。 ,如果没有,您也必须提供。

关于c++ - 在链表中重载 << 运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14866356/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com