2016-08-17 4 views
0

関数に渡されるパラメータはNULLになりますか?私は次のようにリンクリストを逆にする再帰関数を書きました

struct node{ 
int val; 
struct node *next; 
}; 
//Global pointer to structure 
struct node *start=NULL,*head=NULL; 


//*Function to input node* 

void create(int data){ 

struct node *temp; 
temp=(struct node *)malloc(sizeof(struct node)); 
if(start == NULL){ 
    temp->val=data; 
    temp->next=NULL; 
    start=temp; 
    head=temp; 
} 
else{ 
    temp->val=data; 
    temp->next=NULL; 
    head->next=temp; 
    head=temp; 
    } 
    } 

    *Function to reverse the linked list* 
    void* rev(struct node *prev,struct node *cur){ 
     if(cur!=NULL){ 
     printf("Works"); 
     rev(cur,cur->next); 
     cur->next=prev; 
    } 
    else{ 
     start=prev; 
    } 

} 

そしてメインの関連コードは次のとおりです。

main(){ 
    struct node *temp; 
    temp=start; 
    /*Code to insert values*/ 
    rev(NULL,temp); 
    } 

今のコードは、入力を受け取り、完全にそれを印刷しますが、私の後rev()関数を呼び出すと、同じトラバーサル関数は何も出力しません。 私はラインによってデバッガの行のコードを実行しなかったのnそれは私に次のような出力が得られた:curは、if何とかNULLであるため、また

REV(PREV = 0x0の、CUR = 0x0の)

rev()の部分は実行されず、elseのみが一度だけ実行されます。 create()関数で入力を取得すると、リンクリストの最初の要素に更新を開始し、メインでもprintステートメントがそれを証明します。 しかし、なぜ関数rev()は常に入力パラメータをNULLとして受け取るのですか?

追加情報が必要な場合は、ご意見ください。

答えて

0

コードに固有の問題:main()機能には、反転機能をテストするのに十分なコードがありません(ノードを作成しないなど)。あなたのcreate()ルーチンは実際にはheadtailポインタが正しく動作するようにする必要がありますが、現在のheadstartでは正しく動作しません。リバーサル機能は先頭/開始ポインタを維持しますが、テールポインタは処理しません。あなたはifelse節に冗長コードがありますが、これは条件文から引き出すことができます。あなたはvoidの代わりにrev()void *と宣言しました。

私はいくつかのスタイルの問題と一緒に上記の変更に対処して、以下のコードを作り直しました:あなたは内のノードを解放するルーチンを追加する必要があり

> ./a.out 
1 2 3 4 5 6 7 8 9 10 
10 9 8 7 6 5 4 3 2 1 
10 9 8 7 6 5 4 3 2 1 0 
> 

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

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

// Global pointers to structure 
struct node *head = NULL, *tail = NULL; 

// Function to add node 

void create(int data) { 

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

    temporary->value = data; 
    temporary->next = NULL; 

    if (head == NULL) { 
     head = temporary; 
    } else { 
     tail->next = temporary; 
    } 

    tail = temporary; 
} 

// Function to reverse the linked list 

void reverse(struct node *previous, struct node *current) { 
    if (current != NULL) { 
     reverse(current, current->next); 
     current->next = previous; 
    } else { 
     head = previous; 
    } 

    if (previous != NULL) { 
     tail = previous; 
    } 
} 

void display(struct node *temporary) { 
    while (temporary != NULL) { 
     printf("%d ", temporary->value); 
     temporary = temporary->next; 
    } 
    printf("\n"); 
} 

// And the related code in main is: 

int main() { 

    /* Code to insert values */ 
    for (int i = 1; i <= 10; i++) { 
     create(i); 
    } 

    display(head); 

    reverse(NULL, head); 

    display(head); 

    create(0); 

    display(head); 

    return 0; 
} 

OUTPUTリンクされたリスト。

+0

ああ!お疲れ様でした。私は 'rev()'関数が何か問題があったのかどうかまだ分かりません。私の 'create()'は本当に面倒です。 ありがとうもう一度:) – Shanky

関連する問題