2017-05-24 5 views
0

リンクリストの中間要素を見つけようとしていますが、セグメンテーションフォルトが発生しています。これは、私のウサギのアルゴリズムの実装です:リンクされたリストの中の要素を見つける際にセグメンテーションフォルトが発生する

//fast slow pointer method 
void ptMiddle(struct node **head_ref) 
{ 
    struct node *fast = (*head_ref); 
    struct node *slow = (*head_ref); 
    fast = fast->next; 

    while(fast!=NULL) 
    { 
     // printf("%d%d",slow->data,fast->data); 
     slow = slow->next; 
     fast = fast->next->next; 
    } 
    printf("Middle elemnet is:%d\n",slow->data); 
} 

int main() 
{ 
    struct node * head=NULL; 
    push(&head,1); 
    push(&head,2); 
    push(&head,3); 
    push(&head,4); 
    printList(&head); 
    printf("M:%d\n",middleNode(&head)->data); 
    printf("here"); 
    append(&head,5); 
    append(&head,6); 
    printList(&head); 
    printf("M:%d\n",middleNode(&head)->data); 
    printf("here"); 
    ptMiddle(&head); 

    return 0; 
} 

助けてください。

+2

'fast-> next'が 'NULL'の場合、' push'の実装には – RoiHatam

+3

'fast-> next-> next;がありません。 –

+0

は[mcve]を提供します。 – BLUEPIXY

答えて

0

あなたの問題はラインである:最初にあなたがBノードへの高速ポインティングになりfast = fast->nextを、実行することで起動し、A -> B -> NULL

fast = fast->next->next; 

は、あなたがリンクリスト内の2つの要素を持っている想像してみてください。

whileループを入力すると、B->next->nextを取得しようとすると、明らかに存在しないNULL->nextになります。

実装が間違っているため、このケースを避けるようにしてください。 whileは次のように変更することができます:

while(fast!=NULL && fast->next != NULL) 

これで解決します。

要素のペア数の場合、常に左にある中間の要素を取得することに注意してください。だからA -> B -> NULLにはノードAがあります。

+0

ありがとう、私はここの問題を理解した –

関連する問題