如何实现返回弹出的"元素(即数据/值)的函数?(链接列表堆栈) [英] How to implement a 'Pop' function that returns the "popped" element (i.e the data/value) ? (linked list stacks)

查看:17
本文介绍了如何实现返回弹出的"元素(即数据/值)的函数?(链接列表堆栈)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

不知道如何实现单个函数,同时弹出元素并将其作为返回值返回。

到目前为止,我看到的都是返回指向新堆栈头的指针的POP函数。


这是一个开始,但是...

#define VALUE int

typedef struct node_t {
    VALUE item;
    struct node_t *next;
} node;

.
.
.

// Function
VALUE pop(node *stack_head) {

    // Used to store the node we will delete
    node *deleteNode = stack_head;

    // Error Checking        //  <<====== (btw, is this actually necessary ?)
    if (!deleteNode || !stack_head) {

        if (!stack_head) fprintf(stderr, "
Pop failed. --> ...
");
        if (!deleteNode) fprintf(stderr, "
Pop Failed. --> ...
");
        return 0;
    }

    // Storing the value in a variable
    VALUE popped_item = stack_head->item;

    // Updating the head
    stack_head = stack_head->next;    <<====== THERE'S A PROBLEM HERE ! (i think)

    // Freeing/Deleting the 'popped' node
    free(deleteNode);

    // Return 'popped' value
    return popped_item;
}

。 。 。

stack_head = stack_head->next;

实际上不会更改指针stack_head(即堆栈的头部)所指向的地址...因此,第一个POP确实返回了该值,但随后的POP返回错误。

是,因为它是局部变量,但如何将实际指针(指向堆栈头部的指针)更改为指向新的堆栈头部?

推荐答案

参数stack_head是函数pop的本地参数,因此当您修改它时,结果在函数外部不可见。

您需要传递要修改的变量的地址,然后在函数中取消引用POINTER参数以更改它所指向的内容。

因此将您的函数更改为:

VALUE pop(node **stack_head) {

    node *deleteNode = *stack_head;

    if (!*stack_head) {
        fprintf(stderr, "
Pop failed. --> ...
");
        return 0;
    }

    VALUE popped_item = (*stack_head)->item;

    *stack_head = (*stack_head)->next;

    free(deleteNode);
    return popped_item;
}

这样称呼它:

node *stack_head = NULL;
// do something to push onto the stack
VALUE v = pop(&stack_head);

这篇关于如何实现返回弹出的&quot;元素(即数据/值)的函数?(链接列表堆栈)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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