繁体   English   中英

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

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

我在理解结构时遇到了一些麻烦,如果你们中的任何人能解释 function 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;
}

这是一个糟糕的 function 定义。 例如,它的返回值会让 function 的用户感到困惑:返回值 -1 是存储在堆栈中的实际值还是错误代码。

例如,在 function 中的其他任何地方都没有使用变量值的使用初始化器

int retval = -1;

或者

node_t * next_node = NULL;

function 可以通过以下方式定义

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;
}

function 可以这样称呼

node_t *head = NULL;
//...

int value;

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

在循环中使用这样的 function 也很方便。 例如

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

function 在做什么?

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

    int success = *head != NULL;

that is when *head is equal to NULL the function returns 0 - the value of the expression *head != NULL in this case this means for the user of the function that the stack was empty and there is nothing to pop.

否则,将存储在堆栈中的值复制到参数value中,并从列表中删除保留该值的节点,并释放其 memory。 function 返回变量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;
}

程序 output 是

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM