I made this C++ doubly linked list implementation and it seems to work right, handle everything well, and not have any errors. However, I've been working with it for a while and would like some fresh eyes to take a look and see if I am missing anything large or if my code contains any 'gotchas'.
Side note: I ran valgrind on several tests of this implementation and never got any memory leaks so I suspect it is handling that end of this correctly.
DLL.H
#ifndef DLL
#define DLL
class DoublyLinkedNode {
public:
int info;
DoublyLinkedNode *next, *prev;
DoublyLinkedNode() {
next = prev = 0;
}
DoublyLinkedNode(int nu, DoublyLinkedNode *ne = 0, DoublyLinkedNode *pre = 0) {
info = nu;
next = ne;
prev = pre;
}
};
class DoublyLinkedList {
private:
DoublyLinkedNode *head, *tail;
public:
DoublyLinkedList() {
head = tail = 0;
}
~DoublyLinkedList();
bool isEmpty() const {
return head == 0;
}
void addToHead(int);
void addToTail(int);
int removeFromHead();
int removeFromTail();
void remove(int);
bool isInList(int) const;
};
#endif
DLL.cpp
#include <iostream>
#include "DLL.h"
DoublyLinkedList::~DoublyLinkedList() {
for (DoublyLinkedNode *p; !isEmpty();) {
p = head->next;
delete head;
head = p;
}
}
void DoublyLinkedList::addToHead(int n) {
if(head == 0){
head = new DoublyLinkedNode(n);
tail = head;
return;
}
DoublyLinkedNode *tmp = new DoublyLinkedNode(n, head);
head->prev = tmp;
head = tmp;
}
void DoublyLinkedList::addToTail(int n) {
if (tail != 0) {
tail = new DoublyLinkedNode(n, 0, tail);
tail->prev->next = tail;
} else {
head = tail = new DoublyLinkedNode(n);
}
}
int DoublyLinkedList::removeFromHead() {
int el = head->info;
if(head == tail) {
delete head;
head = tail = 0;
} else {
head = head->next;
delete head->prev;
head->prev = 0;
}
return el;
}
int DoublyLinkedList::removeFromTail() {
int el = tail->info;
if(head == tail) {
delete tail;
head = tail = 0;
} else {
tail = tail->prev;
delete tail->next;
tail->next = 0;
}
return el;
}
void DoublyLinkedList::remove(int n) {
if (head != 0) {
if(head == tail) {
delete head;
head = tail = 0;
}
if(head->info == n) {
removeFromHead();
return;
}
if(tail->info == n) {
removeFromTail();
return;
}
DoublyLinkedNode *tmp;
tmp = head;
while(tmp != 0) {
if (tmp->info != n) {
tmp = tmp->next;
} else {
tmp->prev->next = tmp->next;
tmp->next->prev = tmp->prev;
delete tmp;
tmp = 0;
//return;
}
}
}
}
bool DoublyLinkedList::isInList(int el) const {
DoublyLinkedNode *tmp;
for (tmp = head; tmp != 0 && !(tmp->info == el); tmp = tmp->next);
return tmp != 0;
}
DLL.h/.c
is a bad name for the source files. People will think it is some code related to Dynamic Link Libraries. \$\endgroup\$