[C] Doubly linked list (full source) 12-18-2014, 02:14 PM
#1
There will be no tutorial here.. If you want me to break it all down, I can, but this is just for people to use:
DoublyLinkedList.h
DoublyLinkedList.c
You don't have to use the wrapper functions if you don't want. It just lets you traverse the list more freely (if done manually)
DoublyLinkedList.h
Code:
#ifndef DLLTYPE_H
#define DLLTYPE_H
/*this lets us easily change our types*/
#define DLLDT int
struct DLLNode
{
DLLDT data;
struct DLLNode *p, *n; //parent and next
};
struct DLLType
{
struct DLLNode *head;
struct DLLNode *tail;
};
typedef struct DLLType DLLType;
void DLLInit(DLLType list);
void DLLInsert(DLLType list, DLLDT obj);
DLLDT DLLGet(DLLType list, int index);
void DLLRemove(DLLType list, int index);
int DLLCount(DLLType list);
void DLLFree(DLLType list);
struct DLLNode *DLLGetObj(DLLType list, int index);
#endifDoublyLinkedList.c
Code:
#include "DoublyLinkedList.h"
#include <stdlib.h>
void DLLInit(DLLType list)
{ list.head = list.tail = NULL; }
void DLLInsert(DLLType list, DLLDT obj)
{
struct DLLNode *inNode = malloc(sizeof(struct DLLNode));
inNode->data = obj;
inNode->n = NULL;
if (list.head == NULL)
{
inNode->p = NULL;
list.head = list.tail = inNode;
}
else
{
inNode->p = list.tail;
list.tail->n = inNode;
list.tail = inNode;
}
}
DLLDT DLLGet(DLLType list, int index)
{
struct DLLNode *c = list.head;
int i;
for (i = 0; i < index; i++, c = c->n);
return c->data;
}
struct DLLNode * DLLGetObj(DLLType list, int index)
{
struct DLLNode *c = list.head;
int i;
for (i = 0; i < index; i++, c = c->n);
return c;
}
void DLLRemove(DLLType list, int index)
{
struct DLLNode *c = DLLGetObj(list, index);
c->p->n = c->n;
c->n->p = c->p;
free(c);
}
int DLLCount(DLLType list)
{
struct DLLNode *c = list.head;
int i;
for (i = 0; c != NULL; i++, c = c->n);
return i;
}
void DLLFree(DLLType list)
{
struct DLLNode *c = list.head, *c2;
while (c)
{
c2 = c->n;
free(c);
c = c2;
}
}You don't have to use the wrapper functions if you don't want. It just lets you traverse the list more freely (if done manually)


























![[+]](https://sinister.li/images/modern/collapse_collapsed.png)