Last active
January 6, 2019 21:16
-
-
Save benapie/aa200b937771991f147c9f183f3c6783 to your computer and use it in GitHub Desktop.
Simple circularly linked list implementation in C++ with insert and delete functions.
This file contains 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 circularly linked list. | |
*/ | |
class Node { | |
public: | |
Node *next = nullptr; | |
int data; | |
}; | |
/** | |
* Simple structure for a circularly linked list which utilises the node data structure. | |
*/ | |
class CircularlyLinkedList { | |
public: | |
Node *cursor = nullptr; | |
int size = 0; | |
CircularlyLinkedList() = default; | |
/** | |
* Inserts a new node to the right of the cursor (if exists). | |
* @param data is the data of the new node. | |
*/ | |
void Insert(int data) { | |
Node *node = new Node(); | |
node->data = data; | |
if (size == 0) { | |
node->next = node; | |
cursor = node; | |
} else { | |
node->next = cursor->next; | |
cursor->next = node; | |
} | |
size++; | |
} | |
/** | |
* Deletes the first node found with the matching data. | |
* @param data is the data of the node to delete. | |
*/ | |
void Delete(int data) { | |
if (size == 0) { | |
return; | |
} | |
if (size == 1 && cursor->data == data) { | |
cursor = nullptr; | |
} else { | |
Node *node = cursor->next; | |
Node *prev = cursor; | |
for (int i = 1; i < size; ++i) { | |
if (node->data == data) { | |
prev->next = node->next; | |
return; | |
} | |
prev = node; | |
node = node->next; | |
} | |
} | |
size--; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment