在写出元素时,我的链表有问题: 运行main.cpp时,我得到以下输出:
myList.endInsert(5);
cout << myList << endl; output: nothing
myList.headInsert(3);
cout << myList << endl; output : 3
myList.headInsert(2);
cout << myList << endl; output : 3 2
我认为prboble可能是在headinsert或我如何构建我的运算符&gt;&gt;: headin的编码器:
void IntList::headInsert(int the_number)
{
if (head == NULL) //if list is empty
{
head = new IntNode; //create new dynamic variable
head -> data = the_number; //add value to new variable
head -> link = NULL; // }
else
{
NodePtr temp = new IntNode;
temp -> data = the_number;
temp ->link = head; //temp pointer becomes head
head = temp; //head becomes temp
}
**And here is the friend function for the operator:**
ostream& operator <<(ostream& outs, const IntList& lis)
{
for(NodePtr temp = lis.head; temp->getLink() != NULL; temp = temp->getLink())
{
if( temp->getLink() != NULL)
{
outs << " ";
outs << temp->getData();
}
}
return outs;
}
任何人都可以对可能出现的问题有所了解吗?
提前致谢!
答案 0 :(得分:1)
你不打印你的最后一项...
for(NodePtr temp = lis.head; temp != NULL; temp = temp->getLink())
{
outs << " ";
outs << temp->getData();
}
应该这样做(未经测试:)。
答案 1 :(得分:0)
插入第一个元素
时head->link == null;
以后打印支票时
if( temp->getLink() != NULL)
{
outs << " ";
outs << temp->getData();
}
你不打印第一个元素,因为它是null。
卸下:
if( temp->getLink() != NULL)
它应该有效
答案 2 :(得分:-1)
ostream& operator <<(ostream& outs, const IntList& lis)
{
for(NodePtr temp = lis.head; temp != NULL; temp = temp->getLink())
{
//if( temp->getLink() != NULL)
{
outs << " ";
outs << temp->getData();
}
}
return outs;
}
就是这样!现在必须工作!