a slightly generic C++ linked list I wrote to avoid having to write one every time I need one.
And don't butcher me if it doesn't work!! I take no responsiblity!!!!
/*
linkedList.h
header file for a generic singly-linked list, using the node-chain method.
data is integers, to make it simple. change as needed.
*/
#ifndef LINKEDLIST_H
#define LINKEDLIST_H
#include
class node;
class linkedList
{
public:
linkedList();
~linkedList();
int display(int nodeName);
//int search(int value);
void insert(int value, int nodeName);
void remove(int nodeName);
private:
node *first;
};
class node
{
friend linkedList;
private:
int data;
node *link;
};
#endif //LINKEDLIST_H
/*
linkedList.cpp
the source file for a generic linked list, using the chain->node method.
data is an int to make it simple.
*/
#include
#include "linkedList.h"
linkedList::linkedList()
{
first = 0;
}
linkedList::~linkedList()
{
node *next;
while(first)
{
next = first->link;
delete first;
first = next;
}
}
//bool linkedList::find(int nodeName)
//{
int linkedList::search(int value)
{
node *current = first;
int index = 1;
while(current && current->data != value)
{
current = current->link;
index++;
}
if(current) return index;
return 0;
}
void linkedList::insert(int value, int nodeName)
{
//if (nodeName < 0) throw OutOfBounds();
node *p = first;
for (int index = 1; index < nodeName && p; index++)
{
p = p->link;
}
// if(nodeName > 0 && !p)
//throw OutOfBounds();
node *y = new node;
y->data = value;
if(nodeName)
{
y->link = p->link;
p->link = y;
}
else
{
y->link = first;
first = y;
}
return;
}
void linkedList::remove(int nodeName)
{
//if(nodeName < 0) throw OutOfBounds();
node *p = first;
if(nodeName == 1)
{
first = first->link;
}
else
{
node *q = first;
for(int index = 1; index < nodeName - 1 && q; index++)
{
q = q->link;
}
// if(!q || !q->link)
//throw OutOfBounds();
p = q->link;
q->link = p->link;
}
delete p;
return;
}