I'm writing a program that randomly creates a list of integers using a node class then splits the list at a certain value and sorts the resulting two lists then outputs them. right now I get no syntax errors, but I keep getting a segmentation fault. I bolded the statement I get a seg fault at.
Code:
NODE.H
----------
//node class that holds int data and has accessor functions and a
//constructor
#include <cstdlib> //for NULL
class node
{
public:
node(int the_data = int(), node* link_field = NULL)
{data = the_data; link = link_field;}
void set_link(node* link_field) {link = link_field;}
void set_data(int value) {data = value;}
int get_data() {return data;}
const int get_data() const {return data;}
node* get_link() {return link;}
const node* get_link() const {return link;}
private:
int data;
node* link;
};
void head_insert (node*& head, node*& n1);
void sort_list (node*& head);
node* split_list(const int& value, node*& head);
NODE.CC
-----------
#include <cstdlib>
#include "node.h"
using namespace std;
void head_insert(node*& head, node*& n1)
{
n1->set_link(head);
head = n1;
}
node* split_list(const int& value, node*& head)
{
node* head1, *head2, *temp;
while (head != NULL)
{
temp = head;
if (temp->get_data() < value)
{
head = head->get_link();
head_insert(head2, temp);
}else if (temp->get_data() >= value)
{
head = head->get_link();
head_insert(head1, temp);
}
}
head = head1;
return head2;
}
void sort_list(node*& head)
{
int temp;
for (node* ptr = head; ptr != NULL; ptr = ptr->get_link())
{
for (node* cursor = ptr; cursor != NULL; cursor = cursor->get_link())
{
if (cursor->get_data() > ptr->get_data())
{
temp = ptr->get_data();
ptr->set_data(cursor->get_data());
cursor->set_data(temp);
}
}
}
}
MAIN.CC
-----------
#include <iostream>
#include <cstdlib>
#include "node.h"
using namespace std;
int main()
{
node* n1, *head, *head1, *temp;
int value;
srand(time(NULL));
cout << "Please enter a value to split the list at: \n";
cin >> value;
n1 = new node;
n1->set_data(rand()%25+1);
head = n1;
for (int i = 0; i < 10; i++)
{
n1->set_link(new node);
n1 = n1->get_link();
n1->set_data(rand()%25+1);
}
temp = head;
//right here is where I get a segmentation fault. if I put a cout
//statement inside the loop it prints the values though....it's
//weird
while (temp != NULL)
{
cout << temp->get_data();
temp = temp->get_link();
}
head1 = split_list(value, head);
sort_list(head1);
sort_list(head);
temp = head;
cout << "Numbers over the split: ";
while (temp != NULL)
{
cout << temp->get_data();
temp = temp->get_link();
}
temp = head1;
cout << endl << "Numbers under the split: ";
while (temp != NULL)
{
cout << temp->get_data();
temp = temp->get_link();
}
return 0;
}
please help