I want to write a very simple Linked List with only 3 methods Append, Remove and Print. This is not for production and is to be treated as code that could be used in an interview or a quick and dirty prototype. I'm really curious about the approach I've taken here to ensure no duplicates appear in my Linked List. I feel the data structure will be much easier to work with if remove any complexity around duplicate data and want to use this Linked List to implement a Stack, or Queue, or Binary Search Tree etc. I had int data before as the member data field for my Linked List and don't want to make this overly complex by introducing a concept of ids.
First I'd like to know if my member functions for the Linked List have any edge cases I am not catching and any improvements I can make to run time efficiency . Anyway I can simplify this code further with c++11 features, shorter variable names or any other suggestions would be appreciated too.
#include <iostream>
using namespace std;
struct Node
{
int id;
Node* next;
Node(int id) : id(id), next(nullptr) { }
void append(int newId) {
Node* current = this;
while (current->next != nullptr) {
if (current->id == newId) {
return;
}
else {
current = current->next;
}
}
current->next = new Node(newId);
}
void remove(int targetId) {
Node* current = this;
Node* previous;
while (current->id != targetId) {
if (current->next != nullptr) {
previous = current;
current = current->next;
}
else {
cout << "node not found :(\n";
return;
}
}
if (current->next == nullptr) {
delete current;
previous->next = nullptr;
}
else {
Node* danglingPtr = current->next;
current->id = current->next->id;
current->next = current->next->next;
delete danglingPtr;
}
}
void print() {
if (this->next == nullptr) {
cout << this->id << endl;
}
else {
cout << this->id << " ";
this->next->print();
}
}
};
int main()
{
Node list(1);
list.append(2);
list.append(3);
list.append(4);
list.print();
list.remove(3);
list.print();
list.remove(4);
list.print();
list.remove(1337);
}
Nodeand aListare different things. ANodeis a member of aList(maybe a very simple member) but aListdoes not need to have anyNodes. There are several linked list implementations that we have reviewed here. Have a look at an existing one. \$\endgroup\$