2017-06-25 4 views
1

私が書いていることが正しいかどうかはわかりません。私の戦略は、最初に起点リストの最初のノードによって取得され、それによって1つのノードの新しいリストを作成し(起点リストの次のノードを先頭ノードにしながら)、その後、毎回最初のノードおよびリンクそのリストの先頭になることで、新しい逆のリストになります。ここで私はこれまでやっていることです:リンクリストを参照で逆にする関数を記述しようとしています

typedef struct node { 
    int data; 
    struct node *next; 
} Node; 

void reverseList(Node **head) { 
    Node *curr = *head;  // 
    Node *new_node = *head;  
    Node *prev = NULL; 

    new_node->next = NULL; //the new list is to end with the first node of the origin list// 

    while (curr != NULL) {  //traverse through the whole list// 
     curr = curr->next; 
     prev = curr;   //getting the next first node// 
     prev->next = new_node; //and making it linked to the new list// 
    } 

    *head = new_node; //the new, reversed list// 
} 
+0

あなたに少し変更しreverseList機能を与えるあなたはコードが正しいかどうかということを自分でチェックしてみましたか? –

+0

ループを開始する前に、 'head-> next 'を' NULL'に設定するので 'while'ループは1回だけ実行されます。 –

+0

私はNULLの隣にhead->を設定していません... – NoaRoth

答えて

1

あなたのコード内の論理エラーがあります -
は、コードセグメントを守ってください。

Node* new_node=*head;  
Node* prev=NULL; 

new_node->next=NULL; 

最初の行は、最後の行ながら、headnew_nodeを設定し、 new_nodenextポインタをNULLに設定します。したがって、効果的にhead->nextNULLに設定しています。その結果、whileループは最大で1回実行されます。

ここで私は

void reverseList(Node** head) 
{ 
    Node* curr=*head; 
    Node *temp;  
    Node* prev=NULL; 

    while(curr!=NULL)  
    { 
     temp = curr->next; // keep track of the current nodes next node. 
     curr->next = prev; // reverse the link for the current node 
     prev=curr; // current node becomes the previous node for next iteration 
     curr=temp; // now the initially next node becomes the current node for next iteration 
    } 

    /* 
     After the end of the whiie loop, prev points to the last node. 
     So the change *head to point to the last node. 
    */ 

    *head = prev; 

} 
関連する問題