【发布时间】:2018-04-23 15:43:34
【问题描述】:
无论我检查了多少参考资料,我总是发现我的实现是合理的。 但是,这个程序不起作用,我不知道为什么。 请帮忙。谢谢你。 我有这门课
class intNode
{
int x;
intNode * next;
public:
intNode();
intNode(int y, intNode *p);
setNode(int y, intNode *p);
int getX();
void setX(int y);
void setNext(intNode *p);
intNode* getNext();
};
还有这个类
class intList
{
private:
intNode * head;
public:
intList(); //sets head=NULL
void push( int x);
void print();
}
推送如下
void intList::push(int x)
{
intNode *newNode;
newNode->setX(x);
newNode->setNext(head);
head = newNode;
}
打印如下
void intList::print()
{
intNode *current = head;
cout << "Printing list" << endl;
while(current != NULL)
{
cout << current->getX() << "\t";
current = current->getNext();
}
cout << endl;
}
但不知何故,这段代码在main
intList l;
l.push(5);
l.print();
返回这个奇怪的值:6946556
【问题讨论】:
-
在您的
intList::push函数中,您有一个指针变量newNode。 但是你永远不会让它指向任何地方! -
你永远不会创建节点。此外,您的老师似乎还停留在 90 年代初。
-
无论我检查了多少引用,我总是发现我的实现是正确的。 -- 这是指针必须指向某个有效位置才能使用它的基本原则,我很惊讶你正在尝试编写一个链表类。
-
std::list<>模板呢? -
@S.Toonsi -- 评论部分是给 cmets 的,所以你会收到关于你的代码的 cmets。答案在“答案”框中。几乎所有 C++ 中的链表实现都表明链表中的节点是使用
new分配的——不知道你是否认为这样做没有必要。
标签: c++ class object linked-list