c++ - 操作符“<<”溢出双向链表。C++
问题描述
我无法为我的双向链表创建“<<”的重载函数。
这是我的头文件:
#ifndef SORTEDLIST_H
#define SORTEDLIST_H
#include <iostream>
class SortedList {
private:
typedef struct node {
int data;
node* next;
node* prev;
}*nodePtr;
int theSize;
nodePtr head;
nodePtr tail;
public:
SortedList();
//~SortedList();
void insertItem(int inData);
bool deleteItem(int delData);
friend ostream& operator <<(ostream& ot, const SortedList& sL);
int size() const;
bool empty() const;
};
#endif
这是我的构造函数:
SortedList::SortedList() {
//Set pointers equal to NULL
head = NULL;
tail = NULL;
theSize = 0;
head = new node; //create new node of 3 parts: head, data and prev
tail = new node; //create new node of 3 parts: head, data and prev
head->next = tail; //next partition points to tail
head->prev = NULL; //not necessary to put in?
tail->prev = head; //prev partition points to head
tail->next = NULL; //not necessary to put in?
/*temp->next = tail; //access the node the temp pointer is pointing to, set the 'next' part equal to tail*/
}
这是我无法工作的 ostream 重载函数:
ostream& operator<<(ostream& ot, const SortedList& sL)
{
sL.nodePtr temp;
temp = sL.head->next;
while (temp != sL.tail) {
ot << temp->data << " ";
temp = temp->next;
}
ot << "\n";
}
它一直告诉我 sL.NodePtr、sL.head、sL.tail 无法访问。我确实将它设置为朋友功能,所以我不确定为什么。
解决方案
您的实施存在几个问题operator<<
:
sL.nodePtr
需要SortedList::nodePtr
。while
循环都是错误的。它不考虑空列表,并且忽略tail
非空列表的节点。哦,等等,您的列表使用虚拟节点作为其head
andtail
,这是完全没有必要的,只会使类的设计复杂化。完全摆脱假人。它没有
return
什么。它需要返回ot
。
试试这个:
SortedList::SortedList() {
//Set pointers equal to NULL
head = NULL;
tail = NULL;
theSize = 0;
}
ostream& operator<<(ostream& ot, const SortedList& sL)
{
SortedList::nodePtr temp = sL.head;
while (temp) {
ot << temp->data << " ";
temp = temp->next;
}
ot << "\n";
return ot;
}
或者,您可以使用for
循环而不是while
循环:
ostream& operator<<(ostream& ot, const SortedList& sL)
{
for(SortedList::nodePtr temp = sL.head; temp; temp = temp->next) {
ot << temp->data << " ";
}
ot << "\n";
return ot;
}
推荐阅读
- node.js - 如何将身份验证响应转换为对象数组?
- python - Python Selenium 选择输入
- selenium-webdriver - 如何使用 Selenium 在 .Net 核心中处理 Windows 文件上传?
- python - 在创建新列时使用前一行值
- elasticsearch - 如何找到运行 kibana 的端口?
- c++ - 我应该把我的随机数生成放在哪里以获得随机结果?
- javascript - 连接 ECCONREFUSED ::1:50106
- python - 如何在 OneHotEncoder 和 LabelEncoder 中做 inverse_transform?
- k-means - 对于 kmeans 质心,不相同是否不足以被认为是“不同的”?
- python - Django 在两个不同的多对多字段之间进行过滤