C 打印链接列表。我做错了什么?
我在以下代码中遇到分段错误:C 打印链接列表。我做错了什么?,c,list,pointers,C,List,Pointers,我在以下代码中遇到分段错误: void print_stack(Node * root) { while(root != NULL) { // print the node root = root->next; } } 鉴于此项工作: int print_stack(Node ** root) { Node * tmp = *root; while(*root != NULL) { // print the node *
void print_stack(Node * root) {
while(root != NULL) {
// print the node
root = root->next;
}
}
鉴于此项工作:
int print_stack(Node ** root) {
Node * tmp = *root;
while(*root != NULL) {
// print the node
*root = (*root)->next;
}
*root = tmp;
}
问题是我做错了什么?对于这两个函数,我都将节点指针的地址传递给列表的头部。我试图让第一个函数工作,因为它看起来更理想(没有指针分配,也没有对根指针的永久性更改)。。谢谢
编辑:我已经在这里发布了代码:发布您的所有代码,显示链接列表的初始化-看起来应该可以工作
class Node
{
public:
Node();
Node *next;
};
Node::Node()
{
next = NULL;
}
void print_stack(Node * root)
{
while(root != NULL)
{ // print the node
root = root->next;
}
}
int _tmain(int argc, _TCHAR* argv[])
{
Node *root = new Node();
Node *begin = root;
for (int i=0;i<10;i++)
{
Node *pNew = new Node();
root->next = pNew;
root = pNew;
}
print_stack(begin);
return 0;
}
类节点
{
公众:
Node();
节点*下一步;
};
Node::Node()
{
next=NULL;
}
无效打印堆栈(节点*根)
{
while(root!=NULL)
{//打印节点
根=根->下一步;
}
}
int _tmain(int argc,_TCHAR*argv[]
{
Node*root=新节点();
Node*begin=root;
对于(int i=0;inxt=pNew;
root=pNew;
}
打印堆栈(开始);
返回0;
}
您传递了一个节点指针的地址,而函数只接受一个节点指针
这:
应该是这样的:
print_stack(main);
您在链接中发布的程序中存在编译错误 错误1:
int-print\u堆栈(节点*根)
应该返回int
。但它的定义没有这样做
错误2:在开关情况下,调用print\u stack
时,应该传递类型为Node*
的参数,而不是Node**
。因此,它应该是print\u stack(main);
错误3:在切换函数的
情况u
中,push函数参数应为push(&main,&d);
在“root=root->next”上出现Seg故障行,还是程序中的其他地方?@Jollymorphic:我不这么认为..如果next为NULL,则while循环中的条件应该会导致它中断。第二个函数可以肯定地工作。如果链接中的确切发布代码被编译,您肯定会得到编译错误,而不是运行时错误(即seg错误)@Mahesh:你发现了什么编译器错误?我复制并粘贴了我刚刚发布的代码,并且能够在没有警告的情况下编译它。这是使用GCC 4.4.5Yup,你显示的代码没有问题。问题一定存在于你没有显示给我们的代码中。嗨,杰夫。感谢你花时间键入解决方案。不幸的是,这是它并没有真正帮助我,因为你用C++实现了一个不同的实现。我很好奇我在代码中做了什么错误,以及如何修复它。抱歉造成不便。它可能是任何东西。1)它只是简单的错误类型。2) 您尝试访问根->下一步,它对指向指针的指针不起作用;3)您可能访问“//打印节点”部分中的某些内容,该部分尝试访问数据成员。这就像2)会失败。
print_stack(main);