Creating a simple linked list can't be this hard.. please help

Help! I'm really frustrated I'm trying to create a linked list to test one of my functions I did for homework, but I can't create it!! here's what I have below everytime I try to run it it crashes, can you see what's wrong?

Your help is greatly appreciated!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
struct Node {
    int val;
    Node* link;
};

void push(Node* stack, int number); //supposed to add a node to my list

int main()
{
    Node* p;
    p = NULL;
    push(p, 1);
    push(p,2);
    //crashes here
    cout << p->val; //this should be outputting the value of the item in the 1st node??!!

    return 0;
}

void push(Node* stack, int number)
{
    Node* temp; //this is the new node we will add to the stack
    temp = new Node;
    temp->link = NULL;
    temp->val = number;
    Node* runner = stack;       //runner is supposed to go to the last linked item,
                                    //and then it is set to equal the node i just made (temp)
    while (runner != NULL)
        runner = stack->link;
    runner = temp;
}
On line 11 you set 'p' to NULL.

Nowhere between lines 11 and 15 do you change 'p'.

So 'p' is always going to be NULL when you try to dereference it on line 15, which is why it's crashing.
So you need to pass a pointer to p through your function:
void push(Node** stack, int number);
I don't get it... I passed p into the push function, which is where it supposed to get changed right? In the push function i add a node to it.

1
2
3
4
5
6
7
8
9
   Node* temp; //this is the new node we will add to the stack
    temp = new Node;
    temp->link = NULL;
    temp->val = number;
    Node* runner = stack;       //runner is supposed to go to the last linked item,
                                    //and then it is set to equal the node i just made (temp)
    while (runner != NULL)
        runner = stack->link;
    runner = temp;
Topic archived. No new replies allowed.