ostream & operator<<(ostream &out, const IntList &rhs)
{
IntNode *i = rhs.head;
out << rhs.head;
while (rhs.head != 0)
{
out << " " << i;
i = rhs.head->next;
}
return out;
}
程序编译成功,但不打印任何内容。可能是什么问题?
答案 0 :(得分:0)
I assume that the input list is empty, therefore rhs.head != 0
condition fails? Otherwise it would actually result into infinite loop because rhs.head
is tested instead of i
. I suppose it should have been:
IntNode *i = rhs.head;
out << rhs.head;
while (i != 0) // note the i here
{
out << " " << i;
i = i->next; // again i here
}
The second question is what is out
stream because at least head pointer should be printed there...
答案 1 :(得分:0)
您需要使用i
代替rhs.head
while (i != 0)
{
out << " " << i;
i = i->next;
}
rhs.head != 0
不能被循环中的内容改变,所以如果它是假的,循环将永远不会运行,如果它是真的,它将永远循环。
同样i = rhs.head->next;
将始终将i
设置为第二个节点(头部后面的节点),而不是i
之后的节点。