私の再帰スキルはかなり錆びています。私はこの問題について考えていて、長い間フォーラムを検索しましたが、まだ理解できません。今、私はスタンフォード CS ed ライブラリからリンクされたリスト コードを再帰的に逆に見ています。
#include <stdio.h>
struct Node {
int x;
struct Node *next;
};
void Reverse(struct Node ** headRef){
struct Node* first;
struct Node* rest;
if(*headRef==NULL)
return;
first= *headRef;
rest= first->next;
if(rest==NULL)
return;
Reverse(&rest);
printf("Rest%d\n", (rest)->x); // I added this line to print rest
first->next->next=first;
first->next=NULL;
*headRef=rest;
}
void printList(struct Node* head){
if(!head)
return;
else{
printf("%d ", head->x);
printList(head->next);
}
}
void main(){
struct Node *head;
struct Node * node1= (struct Node*) malloc(sizeof(struct Node));
struct Node * node2= (struct Node*) malloc(sizeof(struct Node));
struct Node * node3= (struct Node*) malloc(sizeof(struct Node));
struct Node * node4= (struct Node*) malloc(sizeof(struct Node));
head= node1;
node1->next=node2;
node1->x=1;
node2->x=2;
node3->x=3;
node4->x=4;
node2->next=node3;
node3->next=node4;
node4->next=NULL;
Reverse(&head);
}
ここで、リンクされたリスト 1->2->3->4 があるとします。私が理解できないのは、最終的に headRef を 4 に設定する最後の行です。headRef を 2 に設定する必要があると思います。関数を実行しようとすると、次のように出力されました。
4
4
4
変数残りの場合。
ただし、Reverse 関数の最後の行をコメントアウトすると、リストは逆になりますが、出力されます。
4
3
2.
2 番目の結果は理解できますが、最初の結果はかなり混乱しているように見えました。「*headRef=rest」というステートメントは、変数 rest に対して何かを行いますか? 4 を指し続けるのは何ですか?
また、**headRef の代わりに *headRef を渡すと (最後の行はコメントアウトされていません)、結果が出力されます。
4
3
2
それも。
誰かが記憶の中で何が起こったのか説明してもらえますか? どうもありがとう。