【问题标题】:C program to Reverse a Stack using Recursion [duplicate]C程序使用递归来反转堆栈[重复]
【发布时间】:2014-07-14 03:57:30
【问题描述】:

我遇到了以下使用递归来反转堆栈的函数。对它的工作原理感到困惑。

请帮助我以更简单的方式理解。

void stack_reverse(struct node **head, struct node **head_next)
{
    struct node *temp;

    if (*head_next != NULL)
    {
        temp = (*head_next)->next;
        (*head_next)->next = (*head);
        *head = *head_next;
        *head_next = temp;
        stack_reverse(head, head_next);
    }
}

【问题讨论】:

  • 不值得弄清楚它是如何工作的。这是糟糕的、过于复杂的代码。

标签: c recursion data-structures linked-list tail-recursion


【解决方案1】:

我已经为您注释了代码,这应该可以帮助您理解每一行的作用。如果您仍然遇到问题,那么我强烈建议您阅读指针及其工作原理。指针教程here.

void stack_reverse(struct node **head, struct node **head_next)
{ 
    // Make a temp node.
    struct node *temp;

    // Check if head_next is not null.
    if (*head_next != NULL)
    {
        // Make temp point to the next element of head_next.
        temp = (*head_next)->next;

        // Make next of head_next point to the head.
        (*head_next)->next = (*head);

        // Make head point to head_next.
        *head = *head_next;

        // Make head_next point to temp.
        *head_next = temp;

        // Call the same function again until you are done.
        stack_reverse(head, head_next);
    }
}

【讨论】:

  • 如何在驱动函数中声明**head_next?我通过声明struct node *Start = NULL 运行**head,但是当我输入struct node *Next = (Start)->next_node; 时,出现了某种错误。
  • 想通了。我没有在驱动程序中将**head_next 声明为新节点,而是使用了初始节点和->next。例如。 reverseStack(&MyNode, &MyNode->next).
【解决方案2】:

检查headhead_next 的值在每次迭代中的变化有助于理解函数的工作原理。

迭代开始:

*head: NULL
*head_next: a -> b ->  c -> d -> NULL

第一次致电stack_reverse()

temp = (*head_next)->next;    // temp:       b -> c -> d -> NULL
(*head_next)->next = (*head); // *head_next: a -> NULL
*head = *head_next;           // *head:      a -> NULL
*head_next = temp;            // *head_next: b -> c -> d -> NULL

第二次致电stack_reverse()

temp = (*head_next)->next;    // temp:       c -> d -> NULL
(*head_next)->next = (*head); // *head_next: b -> a -> NULL
*head = *head_next;           // *head:      b -> a -> NULL
*head_next = temp;            // *head_next: c -> d -> NULL

第三次致电stack_reverse()

temp = (*head_next)->next;    // temp:       d -> NULL
(*head_next)->next = (*head); // *head_next: c -> b -> a -> NULL
*head = *head_next;           // *head:      c -> b -> a -> NULL
*head_next = temp;            // *head_next: d -> NULL

第四次致电stack_reverse()

temp = (*head_next)->next;    // temp:       NULL
(*head_next)->next = (*head); // *head_next: d -> c -> b -> a -> NULL
*head = *head_next;           // *head:      d -> c -> b -> a -> NULL
*head_next = temp;            // *head_next: NULL

递归结束。

【讨论】:

    猜你喜欢
    • 2015-06-06
    • 2016-09-27
    • 2021-04-08
    • 2014-04-12
    • 2012-11-13
    • 2014-03-10
    • 2016-01-28
    • 2015-09-12
    • 2017-01-20
    相关资源
    最近更新 更多