【问题标题】:Where head of this Link list points after recursive statement此链接列表的头部在递归语句之后指向的位置
【发布时间】:2021-11-13 10:07:57
【问题描述】:

我有一个简单的链接列表程序,可以创建/打印它,然后打印它的最后 2 个数字(以相反的顺序)

cat link_list.c 
/**
 * C program to create and traverse a Linked List
 */

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

/* Structure of a node */
struct node {
    int data;          // Data 
    struct node *next; // Address 
}*head;


/* 
 * Functions to create and display list
 */
void createList(int n);
void traverseList();
void ReverseList(struct node *);


int main()
{
    int n;

    printf("Enter the total number of nodes: ");
    scanf("%d", &n);

    createList(n);

    printf("\nData in the list \n");
    traverseList();

    ReverseList(head);

    return 0;
}

/*
 * Create a list of n nodes
 */
void createList(int n)
{
    struct node *newNode, *temp;
    int data, i;

    head = (struct node *)malloc(sizeof(struct node));

    // Terminate if memory not allocated
    if(head == NULL)
    {
        printf("Unable to allocate memory.");
        exit(0);
    }


    // Input data of node from the user
    printf("Enter the data of node 1: ");
    scanf("%d", &data);

    head->data = data; // Link data field with data
    head->next = NULL; // Link address field to NULL


    // Create n - 1 nodes and add to list
    temp = head;
    for(i=2; i<=n; i++)
    {
        newNode = (struct node *)malloc(sizeof(struct node));

        /* If memory is not allocated for newNode */
        if(newNode == NULL)
        {
            printf("Unable to allocate memory.");
            break;
        }

        printf("Enter the data of node %d: ", i);
        scanf("%d", &data);

        newNode->data = data; // Link data field of newNode
        newNode->next = NULL; // Make sure new node points to NULL 

        temp->next = newNode; // Link previous node with newNode
        temp = temp->next;    // Make current node as previous node
    }
}


/*
 * Display entire list
 */
void traverseList()
{
    struct node *temp;

    // Return if list is empty 
    if(head == NULL)
    {
        printf("List is empty.");
        return;
    }
    
    temp = head;
    while(temp != NULL)
    {
        printf("Data = %d\n", temp->data); // Print data of current node
        temp = temp->next;                 // Move to next node
    }
}

static count=0, k=2;

ReverseList(struct node *head)
{
    if (head == NULL)
        return;
    else {
        ReverseList(head->next);
        count++;
        if (count <= k)
            printf("Data = %d\n", head->data);
    }
}

对于输入 1 2 3 ,它会首先正确打印 3 2 1 然后 3 2 但我对以下内容感到困惑:

    if (head == NULL)
        return;

用 return; 返回的究竟是什么,以及 head 在后面指向的位置
反向列表(头->下一个);声明?

【问题讨论】:

  • 你的问题是什么?
  • 在编写任何涉及列表或树或类似链接结构的代码之前,我建议您使用铅笔和纸来绘制所有操作。为节点绘制方框,为所有指针绘制箭头。执行操作时擦除并重新绘制箭头。在执行此操作时,记下您执行的操作的编号列表。做这一切,直到你得到一些似乎可以工作的东西,然后将编号列表转换为代码以执行操作。
  • 当你开始实现算法时,一点一点地去做。将上一步(绘图和制作操作列表)中的所有点划分为更小更简单的步骤,并继续细分这些步骤,直到无法进一步划分它们。然后逐个实现每个小子步骤,在启用额外警告的情况下构建(您将其视为必须修复的错误)并进行测试。只有当它构建干净并且工作时,你才能继续下一个小步骤。
  • 然后,当您的某个小块出现问题时,您可以使用调试器逐语句逐句执行相关代码,同时监控变量及其值。再次使用铅笔和纸来绘制您执行的操作,并将它们与您拥有的原始绘图和逐项(和细分)列表进行比较。如果与您在纸上的内容有任何偏差,那么这可能就是问题所在。
  • @AlexF, 但是在 ReverseList(head->next) 之后 head 为空; ,它怎么能成功打印head->data,这是我的主要疑问?

标签: c recursion reverse singly-linked-list function-definition


【解决方案1】:

假设我们有一个简单的三节点列表,如下所示:

1 -> 2 -> 3

当我们最初调用ReverseList 时,我们将1 节点作为head 传递,我们有这个调用链:

反向列表(1 -> 2 -> 3 -> NULL) 反向列表(2 -> 3 -> NULL) 反向列表(3 -> NULL) 反向列表(空) 打印(3) 打印(2) 打印(1)

【讨论】:

  • 其实@Alex F 已经指出,在 ReverseList(head->next); 之后 head 为 NULL在返回路径上,但是 printf 语句中的 head->data 应该会导致一些问题,而不是它以相反的顺序打印出值,如何?
  • @Milan 当head == NULL 函数返回并且不取消引用head。在前面的调用中,局部变量head 不是NULL,它仍然指向3 节点。您必须记住,head 是每次调用中的局部变量,其值将是调用ReverseList(head-&gt;next) 中使用的值,但这不会修改执行该调用的函数中head 的值。
【解决方案2】:

对于初学者,您忘记在函数定义中指定函数的返回类型:

ReverseList(struct node *head)
{
    if (head == NULL)
        return;
    else {
        ReverseList(head->next);
        count++;
        if (count <= k)
            printf("Data = %d\n", head->data);
    }
} 

你必须写:

void ReverseList(struct node *head)

至于你的问题:

我对以下内容感到困惑:

if (head == NULL)
    return;

return; 返回的究竟是什么,以及 head 在 ReverseList(head->next); 之后指向的位置;声明?

那么由于函数的返回类型为void,并且return 语句不包含表达式,因此return 语句不返回任何内容。

函数参数head是函数的局部变量。该函数不会改变文件范围内声明的指针头

struct node {
    int data;          // Data 
    struct node *next; // Address 
}*head;

在函数的第一次调用中,由于这个语句,参数 head 具有全局变量 head 的值:

 ReverseList(head);

如果该值不等于 NULL,则该函数递归调用自身并传递指针 head-&gt;next 的值:

ReverseList(head->next);

因此,在函数本身的第二次递归调用中,其参数head 的值等于head-&gt;next 的值,其中在此表达式中head 是上一次函数调用的函数参数。

也就是参数head首先获取全局变量head的值,然后依次按照序列中下一个节点的数据成员next的值对参数进行初始化。

所以对于包含值为 1、2、3 的节点的列表,您有

第一次调用 参数head等于全局变量head

第二次调用 参数head等于head->next,指向值为1的节点

第三次调用 参数head等于head->next->next,指向值为2的节点

第 4 次调用 参数head等于head->next->next->next,指向值为3的节点

第 5 次调用 参数head等于head->next->next->next->next且等于NULL

注意在函数内使用静态全局变量不是一个好主意

static count=0, k=2;

如果您想再次调用该函数,您需要记住重新初始化它们。最好将变量k设为函数参数。

该函数可以通过以下方式定义,如下面的演示程序所示。

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

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

int push( struct node **head, int data )
{
    struct node *new_node = malloc( sizeof( *new_node ) );
    int success = new_node != NULL;
    
    if ( success )
    {
        new_node->data = data;
        new_node->next = *head;
        *head = new_node;
    }
    
    return success;
}

void display( const struct node *head )
{
    for ( ; head != NULL; head = head->next )
    {
        printf( "%d -> ", head->data );
    }
    
    puts( "null" );
}

size_t display_last_n( const struct node *head, size_t n )
{
    size_t i = 0;
    
    if ( head != NULL )
    {
        i = display_last_n( head->next, n ) + 1;
        
        if ( !( n < i ) )
        {
            if ( i != 1 ) printf( ", " );
            printf( "%d", head->data );
        }
    }
    
    return i;
}

void clear( struct node **head )
{
    while ( *head )
    {
        struct node *tmp = *head;
        *head = ( *head )->next;
        free( tmp );
    }
}

int main(void) 
{
    struct node *head = NULL;
    const int N = 10;
    
    for ( int n = N; n--; )
    {
        push( &head, n );
    }
    
    display( head );
    
    for ( size_t i = 0; i < N; i++ )
    {
        display_last_n( head, i + 1 );
        putchar( '\n' );
    }
    
    clear( &head );
    
    return 0;
}

程序输出为:

0 -> 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 -> 8 -> 9 -> null
9
9, 8
9, 8, 7
9, 8, 7, 6
9, 8, 7, 6, 5
9, 8, 7, 6, 5, 4
9, 8, 7, 6, 5, 4, 3
9, 8, 7, 6, 5, 4, 3, 2
9, 8, 7, 6, 5, 4, 3, 2, 1
9, 8, 7, 6, 5, 4, 3, 2, 1, 0

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-05-01
    • 1970-01-01
    • 2012-09-16
    • 1970-01-01
    • 2014-07-19
    • 1970-01-01
    • 2011-11-19
    • 2011-09-23
    相关资源
    最近更新 更多