2014-05-25 1 views
1

재귀를 사용하여 스택을 리버스하기 위해 아래 함수를 사용했습니다. 그것이 어떻게 작동하는지 혼란 스럽다.재귀를 사용하여 스택을 리버스하는 C 프로그램

좀 더 쉽게 이해할 수 있도록 도와주세요.

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

어떻게 작동하는지 알아볼 가치가 없습니다. 그것은 나쁘고 지나치게 복잡한 코드입니다. – Gene

답변

3

각 코드의 내용을 이해하는 데 도움이되는 코드를 작성했습니다. 그래도 문제가 계속된다면 포인터와 그 작동 방식을 읽어 보시기 바랍니다. 포인터에 대한 자습서 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); 
    } 
} 
+0

드라이버 기능에서'** head_next'를 어떻게 선언할까요? 나는'struct node * Start = NULL'을 선언함으로써'** head'를 실행하지만'struct node * Next = (Start) -> next_node;'를 넣을 때 어떤 종류의 에러가 있습니다. –

+0

그것을 알아 냈습니다. 드라이버에서'** 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 

넷째 전화 : 재귀의

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 

끝.

관련 문제