[英]Operator overloading in Linked List
我將從其他職位搬到這里。 但是這次我可以獲取某種類型的輸出。 但是我似乎無法遍歷我的節點並讓它們分別打印出來,就像它在輸出中的外觀一樣。 這是我到目前為止的內容,也是該程序應輸出的屏幕截圖。
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;
該行將跳過您的第一個元素,並在最后一個元素上導致未定義的行為(可能是段錯誤)。 這應該是out<<p
。
您的operator<<
將不打印任何內容,因為從未分配LList::front
。 它始終為空。
您的推送算法沒有任何意義。 要將某些內容推到列表的后面,您只希望在列表為空的情況下修改head
,但是您需要:
if (_head == 0)
{
_head = _tail = p;
}
else
{
_head ->next(p);
_head = p;
}
如果列表中已經包含條目,為什么將_head
設置為p
? 您的代碼有許多類似的錯誤-邏輯不正確。
最后應該只是:
if (_head == 0)
_head = p;
如果頭部已經有一個節點,則在背面添加一個條目根本不會影響頭部。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.