2016-04-27 10 views
0

私はC++を初めて使用しました。私はリンクリストをC++で実装しています。g ++のセグメンテーションフォールト

/* 
CTCI: 2.4 

Partition a linked list at value x. ALl the noeds less than x comes before 
x and all the nodes more than x come after 
*/ 

#include <iostream> 
using namespace std; 
struct Node 
{ 
    int data; 
    Node *next; 
}; 

Node *create_node(int val){ 
    Node *tmp = new Node(); 

    if (tmp == NULL){ 
     cout<<"Memeory allocation failed"; 
     return 0; 
    } else { 
     tmp->data = val; 
     tmp->next = NULL; 
     return tmp; 
    } 
} 

void createSLL(Node *& head, int d){ 
    Node *tmp = create_node(d); 
    Node *ptr; 
    if (head == NULL) 
     head = tmp; 
    else{ 
     ptr = head; 
     while(ptr->next != NULL) 
      ptr = ptr->next; 
     ptr->next = tmp; 
    } 
} 

void display(Node *head){ 
    Node *ptr = head; 
    if (ptr == NULL) 
     return; 
    while(ptr->next != NULL){ 
     cout<<ptr->data<<"->"; 
     ptr = ptr->next; 
    } 
    cout<<ptr->data<<endl; 
} 

Node *pivotPartition(Node * head, int data){ 
    Node *firsthead = NULL; 
    Node *secondhead = NULL; 
    Node *tmp = head; 

    if(tmp == NULL) 
     return NULL; 

    while(tmp != NULL){ 
     Node *next = tmp->next; 
     if(tmp->data < data){ 
      tmp->next = firsthead; 
      firsthead = tmp; 
     } 
     else{ 
      tmp->next = secondhead; 
      secondhead = tmp; 
     } 
     tmp = next; 
    } 
    if(firsthead == NULL) 
     return secondhead; 
    else 
     tmp = firsthead; 
    while(tmp->next != NULL) 
     tmp = tmp->next; 
    tmp->next = secondhead; 
    return firsthead; 
} 

int main(int argc, char const *argv[]) 
{ Node *head; 
    createSLL(head, 3);createSLL(head, 9);createSLL(head, 7); 
    createSLL(head, 1);createSLL(head, 4);createSLL(head, 8); 
    display(head); 
    Node *p = pivotPartition(head, 4); 

    return 0; 
} 

このコードはg ++のセグメンテーションフォルトを示していますが、このコードをIdeoneで実行するとうまくいきます。 See here

これは多くのプログラムで発生しています。 g ++の最新バージョンがあり、私はubuntuを実行しています。14.04

EDIT: 私のコードは、何も返さないか、pivotPartition関数から何も受け取らない限り動作します。 Node *p = pivotPartition(head, 4);からpivotPartition(head, 4);にコードを変更すると正常に動作します。

+0

これまでに問題を把握するために何をしましたか? – immibis

+1

gdbでデバッグしようとしました。私はこの '#0 0x000000000040099fをcreateSLL(Node *&、int)()に入れます。 #1 0x0000000000400b41 in main()'ここにはまっています。 –

+2

あなたは 'head'を初期化していません。 – user657267

答えて

1

Node * headをmainでNULLで初期化する必要があります。

関連する問題