C++ 链表堆栈上的Pop函数

C++ 链表堆栈上的Pop函数,c++,pointers,linked-list,stack,C++,Pointers,Linked List,Stack,您好,我的pop函数返回的变量有问题。 如果你能帮助我,我会很高兴的。 函数接收到一个指向列表顶部的指针,应该返回答案,但我对指向列表的指针和输入答案有问题 功能代码- int pop(Node* top) { Node* tmp = top; int ans = tmp->next; top = top->next; delete tmp; return ans; } 节点- struct Node { int num; Node* nex

您好,我的pop函数返回的变量有问题。 如果你能帮助我,我会很高兴的。 函数接收到一个指向列表顶部的指针,应该返回答案,但我对指向列表的指针和输入答案有问题

功能代码-

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;

intans=tmp->next似乎是问题的根源。这是试图获取节点中的
下一个
指针,将其转换为
int
,然后返回它。您(几乎可以肯定)想要的是从节点检索数据并返回该数据,类似于
intans=tmp->num


当然,这并不是说代码在其他方面是完美的(例如,它似乎缺乏任何检查错误的尝试,更不用说处理错误),但至少在这种变化下,它有一些机会在某些(理想的)情况下正常工作环境。

如果堆栈为空或其行为未定义,通常此类函数会引发异常。当堆栈为空时,我使用返回值0

int pop( Node * &top )
{
    int value = 0;

    if ( top )
    {
        value = top->num;
        Node *tmp = top;
        top = top->next;
        delete tmp;
    }

    return value;
}
当函数poo具有类型void时,还有另一种方法,即它只返回顶部的元素,而不返回任何内容

如我的文章中所述,您应该将其拆分为两个单独的函数。一个用于获取值,另一个用于弹出(删除)节点

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.");
}

首先,您试图删除
tmp
节点,但top节点仍然存在,并且必须以ans或top->next或在这种情况下top->num返回值。当node
tmp
是一个参数时,为什么要在函数中初始化node
tmp
?为什么节点*&top应该在函数参数中而不是
tmp

value=top->num不能解决这个问题,因为他想要的是链表顶部的指针,而不是通过函数参数输入的随机节点。要解决此问题,节点*tmp
应等于top,然后值应等于tmp->num。否则,所有其他问题都已解决

//编辑

在//编辑之前忽略所有内容,因为所有这些都是关于他的问题的问题,我现在已经知道了。我已经编译了这段代码,它完全适合我

struct Node
{
    int data;
    Node *next;
};

int pop(Node *head)
{
    while(head->next != NULL)
    {
        head = head->next;
    }
    int value;
    Node *tmp;
    tmp = new Node;
    value = head->data;
    tmp = head;
    delete tmp;
    return value;
}

编译代码链接-

已尝试
int-pop(节点*&top)
了吗?看起来函数应该更改
top
的值。@roi hoyli显示如何定义节点。@VladFromi已更新Look@VladfromMoscow我怀疑这是真正的问题。@roi hoyli如果堆栈为空,返回什么?我认为您的答案需要更多的格式,像这样理解你的观点很困难。我会解决格式问题,我真的不明白他的问题是他想删除列表的结尾还是删除最后一个节点的num并将其作为ans返回?好的,我已经修复了所有问题,如果您认为仍然存在错误,请详细解释为什么您认为soI知道我晚了三年,但答案完全错误。该解决方案(1)从堆栈的错误端弹出(2)分配节点而不是删除节点,以及(3)泄漏内存。除此之外,它工作正常;)