链表堆栈上的弹出功能

问题描述:

你好,我从弹出函数返回变量时遇到问题. 如果您能帮助我,我会很高兴. 该函数接收到指向列表顶部的指针,并应返回答案,但是指向列表并整数答案时出现问题.

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.

功能代码-

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

节点-

struct Node
{
int num;
Node* next;
}


Node* top = new Node;

如我的

As mentioned in my comment you should split this up to two separate functions. One to get the value, and another one to pop (remove) the Node

void pop(Node*& top) { // Note the reference. You want to change the current top node.
           // ^
    if ( top ) {
        Node *tmp = top;
        top = top->next;
        delete tmp;
    }
}

int& top(Node* top) {
    if ( top ) {
        return top->num;
    }
    // Throw an appropriate exception if the stack is empty
    throw std::out_of_range("Stack is empty.");
}