This question already has answers here:
Closed 5 years ago.
reversing linked list
(9个答案)
我遇到了下面的函数来使用递归反转堆栈我对它的工作方式感到困惑。
请帮助我用更简单的方式理解。
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);
    }
}

最佳答案

我已经为您注释了代码,这将帮助您理解每一行的功能如果您仍然有问题,那么我强烈建议您仔细阅读指针及其工作原理。指针教程。

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

07-27 18:15