Printing a linked list. What am I doing wrong?
I am getting a segmentation fault in the following code:
void print_stack(Node * root) {
while(root != NULL) {
// print the开发者_运维百科 node
root = root->next;
}
}
Whereas this works:
int print_stack(Node ** root) {
Node * tmp = *root;
while(*root != NULL) {
// print the node
*root = (*root)->next;
}
*root = tmp;
}
The question is what am I doing wrong? For both functions I am passing the address of a Node pointer to the head of the list. I am trying to get the first function to work because it seems more ideal (no pointer allocation and no permanent change to root pointer).. thanks.
EDIT: I have posted the code here: http://dpaste.com/477724/
You passed the address of a Node pointer while the function takes just a Node pointer.
This:
print_stack(&main);
should be this:
print_stack(main);
Post all your code, showing the initialization of the linked list - seems like it should work.
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;
}
There are compilation errors in the program you posted in the link.
Error1: int print_stack(Node * root)
supposed to return an int
. But it's definition isn't doing so.
Error2: In switch case, while calling print_stack
, supposed to pass an argument of type Node*
and not Node**
. So, it should be print_stack(main);
.
Error3: In case u
of switch function, push functions arguments should be push(&main, &d);
精彩评论