A singly (sp) and a Doubly Linked list class to create linked lists. Can be used to make dynamic arrays and could also be templated to work with any data type (this is old code and i didnt know how to at the time). Has been extremely useful to me even in its bare form like this.
Linked List Classes
#include <stdio.h>
#include <iostream.h>
struct item
{
long data;
item *next;
item *previous;
item(void)
{
data = 0;
next = previous = NULL;
}
};
/* Single Linked List
*
* Structure: head -> next -> next .... -> tail (null)
*/
struct SLLIST
{
item *head;
item *tail;
item *current;
unsigned int listcount;
SLLIST(void)
{
head = new item;
tail = current = head;
listcount = 1;
}
~SLLIST(void)
{
item *temp = head;
current = head;
while (current != NULL)
{
current = current->next;
delete temp;
temp = current;
}
}
int operator[](int index) /* index list like a normal array */
{
if(index >= listcount)
index %= listcount; // wrap array
item *temp = head;
for(int i = 0; i < index; i++)
temp = temp->next;
current = temp;
return temp->data;
}
void addnode(int data)
{
tail->next = new item;
tail = tail->next;
tail->data = data;
listcount++;
}
void PrintToConsole(void)
{
item *temp = head;
current = head;
while (current != NULL)
{
current = current->next;
cout << temp->data << "\n";
temp = current;
}
}
};
/* Doubly linked list
*
* Structure: Head <-> next <-> next .... <-> tail (null)
*/
struct DLLIST
{
item *head;
item *tail;
item *current;
unsigned int listcount;
DLLIST(void)
{
head = new item;
tail = current = head;
listcount = 1;
}
~DLLIST(void)
{
item *temp = head;
current = head;
while (current != NULL)
{
current = current->next;
delete temp;
temp = current;
}
}
int operator[](int index) /* index list like a normal array */
{
if(index >= listcount)
index %= listcount; // wrap array
item *temp = head;
for(int i = 0; i < index; i++)
temp = temp->next;
current = temp;
return temp->data;
}
void advance(void)
{
if(current->next != NULL)
current = current->next;
}
void rewind(void)
{
if(current->previous != NULL)
current = current->previous;
}
void addnode(int data)
{
tail->next = new item;
tail->next->previous = tail; // link new back to old tail
tail = tail->next;
tail->data = data;
listcount++;
}
void PrintToConsole(void)
{
item *temp = head;
current = head;
while (current != NULL)
{
current = current->next;
cout << temp->data << "\n";
temp = current;
}
}
};
Dani 4,310 The Queen of DaniWeb Administrator Featured Poster Premium Member
1o0oBhP 4 Posting Pro in Training
Be a part of the DaniWeb community
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.