链表堆栈上的弹出功能 [英] Pop function on Linked list stack

查看:87
本文介绍了链表堆栈上的弹出功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

这篇关于链表堆栈上的弹出功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆