Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Hello I have a problem to returned variable from my pop function. I will be happy if you could help me. The function receives a pointer to the top of the list and should return the answer but I have a problem with a pointer to the list and intger the answer.

Function Code -

int pop(Node* top)
{
    Node* tmp = top;
    int ans = tmp->next;
    top = top->next;
    delete tmp;
    return ans;
}

Node -

struct Node
{
int num;
Node* next;
}


Node* top = new Node;
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
155 views
Welcome To Ask or Share your Answers For Others

1 Answer

The line int ans = tmp->next; appears to be the source of the problem. This is attempting to take the next pointer in the node, convert it to an int, and return it. What you (almost certainly) want is to retrieve the data from the node and return that, with something like int ans = tmp->num;.

Of course, that's not saying the code is perfect otherwise (e.g., it seems to lack any attempt at checking for, not to mention dealing with, errors), but at least with that change, it stands some chance of working correctly under some (ideal) circumstances.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...