0

I a new to C++. I am implementing Linked List in C++.

/*
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;
}

This code gives segmentation fault on g++ but when I run this code on Ideone it works just fine. See here

This is happening for many programs. have latest version of g++ and I am running ubuntu 14.04

EDIT: My code works until I do not return anything or receive anything from pivotPartition function. when I change Node *p = pivotPartition(head, 4); to pivotPartition(head, 4); code works fine.

kaylum
  • 13,833
  • 2
  • 22
  • 31
Amit Tripathi
  • 7,003
  • 6
  • 32
  • 58

1 Answers1

1

You have to initialize Node * head with NULL within main.

orbitcowboy
  • 1,438
  • 13
  • 25