2016-04-27 70 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

编辑: 我的代码工作,直到我不返回任何东西或从pivotPartition函数接收任何东西。 当我将Node *p = pivotPartition(head, 4);更改为pivotPartition(head, 4);时,代码正常工作。

+0

到目前为止,你已经做了什么来弄清楚这个问题? – immibis

+1

尝试通过gdb进行调试。我在main()中获得了这个'#0 0x000000000040099f in createSLL(Node *&,int)() #1 0x0000000000400b41'我卡在这里。 –

+2

你并没有初始化'head'。 – user657267

回答

1

您必须在main中初始化带有NULL的Node *头。