gpt4 book ai didi

c++ - 链表中的运算符重载

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

我从我的另一个职位搬到这里。但是这次我能够获得某种类型的输出。但我似乎无法遍历我的节点并让它们单独打印出来,就像它在输出中的样子一样。这是我目前所拥有的,也是程序应该输出的屏幕截图。

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

主程序.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;

此行将跳过您的第一个元素并在您的最后一个元素上导致未定义的行为(可能是段错误)。这应该是 out<<p .

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

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