Last active
January 6, 2019 20:44
-
-
Save benapie/590b5b808907cb8a4d2265562b197dfc to your computer and use it in GitHub Desktop.
Simple doubly linked list implementation in C++ with find, delete, and insert functions.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Simple node data structure for a doubly linked list. | |
*/ | |
class Node { | |
public: | |
Node *next = nullptr; | |
Node *prev = nullptr; | |
int data; | |
}; | |
/** | |
* Simple data structure for a doubly linked list which utilises the node data structure. | |
*/ | |
class DoublyLinkedList { | |
public: | |
Node *head = nullptr; | |
Node *tail = nullptr; | |
int size = 0; | |
DoublyLinkedList() = default; | |
/** | |
* Insert a new node with specified data into the head of the linked list. | |
* @param data the data to insert into the list. | |
*/ | |
void InsertFront(int data) { | |
Node *temp = new Node(); | |
temp->data = data; | |
if (size == 0) { | |
head = temp; | |
tail = temp; | |
} else { | |
temp->data = data; | |
temp->next = head; | |
temp->next->prev = temp; | |
head = temp; | |
} | |
size++; | |
} | |
/** | |
* Insert a new node with specified data into the tail of the linked list. | |
* @param data the data to insert into the list. | |
*/ | |
void InsertBack(int data) { | |
Node *temp = new Node(); | |
temp->data = data; | |
if (size == 0) { | |
head = temp; | |
tail = temp; | |
} else { | |
temp->data = data; | |
temp->prev = tail; | |
temp->prev->next = temp; | |
tail = temp; | |
} | |
size++; | |
} | |
/** | |
* Finds the node with specified data in the list. | |
* @param data the data to find in the list. | |
* @return the index of the node with the data or -1 if not found. | |
*/ | |
int Find(int data) { | |
Node *temp = head; | |
for (int i = 0; i < size; ++i) { | |
if (temp->data == data) { | |
return i; | |
} | |
temp = temp->next; | |
} | |
return -1; | |
} | |
/** | |
* Delete the node with specified data in the list. | |
* Will delete the first node that it finds and then terminate. | |
* @param data the data to delete from the list. | |
*/ | |
void Delete(int data) { | |
if (size == 0) { | |
return; | |
} | |
if (head->data == data) { | |
head = head->next; | |
head->prev = nullptr; | |
size--; | |
} else { | |
Node *node = head->next; | |
for (int i = 1; i < size; ++i) { | |
if (node->data == data) { | |
node->prev->next = node->next; | |
node->prev = node->prev; | |
size--; | |
return; | |
} | |
node = node->next; | |
} | |
} | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment