Problem with template linked list
the goal of my program is to take in two sets of any regular data type (int, double, char, etc) then be able to manipulate them. so far I'm working on input and output, but it's not working. here's my code so far:
Code:
//NODE.H header for class node. all the functions are inline
---------------------------------------------------------------------------
#ifndef NODE_H
#define NODE_H
#include <cstdlib>
template <class Item>
class node
{
public:
node(Item the_data = Item(), node* link_field = NULL)
{data = the_data; link = link_field;}
//default constructor. sets data = whatever the default
//constructor of the data type is and sets the link = NULL
void set_link(node* link_field) {link = link_field;}
void set_data(Item value) {data = value;}
Item get_data() {return data;}
node* get_link() {return link;}
private:
Item data;
node* link;
};
#endif
//BAG.H header for class bag which is a set of any data type
----------------------------------------------
#ifndef BAG_H
#define BAG_H
#include <cstdlib>
template <class Item>
class bag
{
public:
bag() {head = NULL;}
//default constructor
void print();
//prints with cout
void input();
//inputs with cin and head_insert
void set_head(node<Item>* n1) {head = n1;}
node<Item>* get_head() {return head;}
bool is_element(const Item& value);
//finds if any of the nodes in the set have data = value
//there will be more here later, but right now I just wanna have
//I/O
private:
node<Item>* head;
};
template <class Item>
void head_insert(node<Item>* head, Item value);
//creates a new node at the head of the list
#include bag.template
#endif
BAG.TEMPLATE implementation for class bag
----------------------------------------------------------
#include "node.h"
#include <iostream>
#include <cstdlib>
using namespace std;
template <class Item>
void bag<Item>::input()
{
Item value;
cout << "Please enter a set: \n"; //set will have no spaces
cin >> value;
head_insert(head, value);
while (cin.peek() != '\n')
{
cin >> value;
head_insert(head, value);
}
}
template <class Item>
void bag<Item>::print()
{
node<Item>* temp = head;
cout << "{"; //output is like this {a,b,c,d}
if (head != NULL)
{
cout << temp->get_data();
temp = temp->get_link();
while (temp)
{
cout << "," << temp->get_data();
temp = temp->get_link();
}
cout << "}";
}
}
template <class Item>
void head_insert(node<Item>* head, Item value)
{
node<Item>* temp;
temp = new node<Item>;
temp->set_data(value);
temp->set_link(head);
head = temp;
}
//MAIN.CC application file
-----------------------------------
#include "bag.h"
#include <iostream>
using namespace std;
int main()
{
bag<char> b1, b2;
b1.input();
cout << endl;
b1.print();
cout << endl;
b2.input();
cout << endl;
b2.print();
cout << endl;
return 0;
}
//that should be all you need
I keep getting a segmentation fault when I get to my print function. I'm thinking that either my input function doesn't work right or I'm not setting the end of the list = NULL
please help ASAP