有人可以解释以下代码的函数 pop(更具体地说是变量 retval)吗?

Can someone please explain the function pop (more especifically the variable retval) of the following code?

我在理解结构时遇到了一些困难,如果你们中的任何人能解释函数 pop 以及在此上下文中什么是 retval,我将不胜感激。先感谢您!代码在这里:

 typedef struct node {
     int val;
     struct node * next;
} node_t;

int pop(node_t ** head) {
    int retval = -1;
    node_t * next_node = NULL;

    if (*head == NULL) {
        return -1;
    }

    next_node = (*head)->next;
    retval = (*head)->val;
    free(*head);
    *head = next_node;

    return retval;
}

这是一个错误的函数定义。例如,它的 return 值可能会使函数的用户感到困惑:returned 值 -1 是存储在堆栈中的实际值还是错误代码。

使用了变量值的初始值设定项,其值未在函数中的其他任何地方使用,例如

int retval = -1;

node_t * next_node = NULL;

函数可以这样定义

int pop( node_t **head, int *value ) 
{
    int success = *head != NULL;

    if (success )
    {
        *value = ( *head )->val;

        node_t *tmp = *head;

        *head = ( *head )->next;

        free( tmp );
    }

    return success;
}

而且函数可以这样调用

node_t *head = NULL;
//...

int value;

if ( pop( &head, &value ) )
{
    printf( "The value stored on the top of the stack is %d\n", value );
}

而且在循环中使用这样的函数也很方便。例如

int value;
while ( pop( &head, &value ) )
{
    printf( "%d ", value );
}
puts( "-> the stack is empty." );

函数在做什么?

该函数弹出一个存储在堆栈中的值。如果栈为空

    int success = *head != NULL;

即当 *head 等于 NULL 函数 returns 0 - 表达式的值 *head != NULL 在这种情况下这意味着对于函数的用户,堆栈是空的,没有任何东西可以弹出。

否则存储在栈上的值被复制到参数value中并且保存该值的节点从链表中移除并且它的内存被释放。并且函数 returns 变量 success 的值在这种情况下等于 1.

    if (success )
    {
        value = ( *head )->val;

        node_t *tmp = *head;

        *head = ( *head )->next;

        free( tmp );
    }

    return success;

这是一个演示程序。

#include <stdio.h>
#include <stdlib.h>

typedef struct node 
{
    int val;
    struct node *next;
} node_t;

int push( node_t **head, int value )
{
    node_t *new_node = malloc( sizeof ( node_t ) );
    int success = new_node != NULL;

    if ( success )
    {
        new_node->val  = value;
        new_node->next = *head;
        *head = new_node;
    }

    return success;
}

int pop( node_t **head, int *value ) 
{
    int success = *head != NULL;

    if (success )
    {
        *value = ( *head )->val;

        node_t *tmp = *head;

        *head = ( *head )->next;

        free( tmp );
    }

    return success;
}

int main(void) 
{
    node_t *head = NULL;

    const int N = 10;

    int i = N;

    while ( i != 0 && push( &head, i  ) ) --i;

    int value;

    printf( "The stack contained: " );

    while ( pop( &head, &value ) )
    {
        printf( "%d ", value );
    }
    putchar( '\n' );

    return 0;
}

程序输出为

The stack contained: 1 2 3 4 5 6 7 8 9 10