2016-04-29 12 views
1

私は現在、学校の休憩中にポインタを練習しています。下のリンクリストを逆にする方法を書いていますが、オンラインテストに渡すと失敗します。二重リンクリストをテールから頭に逆転させる

Node* Reverse(Node *head) 
{ 
    int count = 0; 
    struct Node *ptr = head; 

    // return head if NULL 
    if (head == NULL) { 
     return head; 
    } 
    // if the list is only the head, then the reverse is just the head... so nothing changes 
    if((head->next == NULL && head->prev == NULL)){ 
     return head; 
    } 

    //Come here if previous if statements fail, traverse the list until I reach tail which will become the 
    // new head 
    while(ptr->next != NULL){ 
     ptr = ptr->next; 
     count++; 
    } 
    head = ptr; // this is the new head  
    //starting from tail all the way to head swap the "prev" and "next" of each node 
    struct Node *temp = ptr->next; 

    for(int i = 0; i<count; i++){ 
     ptr->next = ptr->prev; 
     ptr->prev = temp; 
     ptr=ptr->next; 
     temp= ptr->next; 
     //count--; 
    } 

    return head; 
} 

私は私が頭から尾にそれを横断しながら、リストを逆にすることはおそらく賢くあることを認識し、私はそれが退屈だと思ったので、私が代わりに頭に尾から始め、それを逆にすることを決めました。 whileループまたはforループに明らかなエラーがあると思われますが、エラーを診断できません。

+0

オンラインテストにはどのようなエラーがありますか? – nobism

+0

'struct Node' - >' Node'または 'Node * head' - >' struct Node * head' – BLUEPIXY

+0

ここにエラーがあります:間違った答えです! 考えられるエラー: 1.関数からNULL値を返しました。 2.ロジックに問題があります – Belphegor

答えて

3

私は、エラーがここにあると思う:

while(ptr->next != NULL){ 
    ptr = ptr->next; 
    count++; 
} 

さんがあなたのリンクリストは、その中に2つの要素を持っているとしましょう。その場合、whileループは1回だけ反復され、countは1になります。forループになると、1回だけ反復されます。つまり、新しいヘッドのポインタを正しく再割り当てしますが、以前は頭部)。

countを0ではなく1に初期化すると、リンクリストの要素数が正しく反映され、forループが正しく実行されます。

編集:ます。また、リストの末尾にセグメンテーションフォルトを避けるために、少しごforループを再構築する必要があります:

Node* temp; 

for (int i = 0; i < count; i++) 
{ 
    temp = ptr->next; 
    ptr->next = ptr->prev; 
    ptr->prev = temp; 
    ptr = ptr->next; 
} 
+0

カウントを1に設定するとsegfaultが発生します。 – Belphegor

+0

さて、私の編集でうまくsegfaultが修正されるはずです:) – skearney

+0

カウントを1に設定すると、forループのエラーがどのように来るのか説明できますか? – Belphegor

1

for(int i = 0; i <= count; i++){ 
    ptr->next = ptr->prev; 
    ptr->prev = temp; 
    temp = ptr; 
    ptr = ptr->next; 
} 

for(int i = 0; i<count; i++){//i<count --> i<=count : Because Not counting last element 
    ptr->next = ptr->prev; 
    ptr->prev = temp; 
    ptr=ptr->next; 
    temp= ptr->next;//<-- bad 
    //count--; 
} 

を置き換えます

または

while(ptr){ 
    ptr->next = ptr->prev; 
    ptr->prev = temp; 
    temp = ptr;//next prev 
    ptr = ptr->next; 
} 
関連する問題