Linked List
#include <iostream>
#include <random>
#include <time.h>
using std::mt19937,
std::cerr;
class Node{
public:
int data;
Node* next = nullptr;
Node* prev = nullptr;
Node(int num = 0):data(num){}
~Node(){
if (next != nullptr){
delete next;
next = nullptr;
}
}
void IncrementBy(int n){
data += n;
if(next != nullptr){
next->IncrementBy(n);
}
}
void print(Node* n){
cerr << n->data;
if(n->next != nullptr){
cerr < ", ";
print(n->next);
}else{
cerr < "\n";
}
}
};
class LinkedList{
public:
Node* head = nullptr;
LinkedList(){
}
~LinkedList(){
deleteList();
}
void AddNode(int i){
if(head == nullptr){
head = new Node(i);
}else if(head->next == nullptr){
head->next = new Node(i);
head->next->prev = head;
}else{
Node* t = head;
while(t->next != nullptr){
t = t->next;
}
if(t->next == nullptr){
t->next = new Node(i);
t->next->prev = t;
}
}
}
Node* getNext(Node* n){
return n->next;
}
void printList(){
if(head != nullptr){
head->print(head);
}
}
void deleteList(){
if(head != nullptr){
delete head;
head = nullptr;
}
}
void IncrementAllBy(int n = 1){
if (head != nullptr){
head->IncrementBy(n);
}
}
void find(Node* h, int i){
if(h->data == i){
//first node in the list
if(h->prev == nullptr && h->next != nullptr){
Node* t = head;
head = head->next;
t->next = nullptr;//this line is important
delete t;
t = nullptr;
if(head->next != nullptr){
find(head->next, i);
}
//the last node in the list
}else if(h->prev != nullptr && h->next == nullptr){
Node* t = h;
h->prev->next = nullptr;
delete t;
t = nullptr;
//a middle node
}else if(h->prev != nullptr && h->next != nullptr){
Node* t = h;
h->prev->next = h->next;
h->next->prev = h->prev;
t->next = nullptr;//this line is important
delete t;
t = nullptr;
if(h->prev->next != nullptr){
find(h->prev->next, i);
}
//There's only one node.
}else if(h->prev == nullptr && h->next == nullptr){
delete head;
head = nullptr;
}
}else{
if(h->next != nullptr){
find(h->next, i);
}
}
}
void removeNumber(int i){
find(head, i);
}
};
int main(){
LinkedList list;//at this point the list is empty
mt19937 rnd(time(NULL));//I was creating nodes that contained random numbers
list.AddNode(0);
list.AddNode(1);
list.AddNode(2);
list.AddNode(0);
list.AddNode(4);
list.AddNode(5);
list.AddNode(0);
/* for(int x = 0; x < 30; x++){
list.AddNode(rnd() % 10);
}
*/
list.printList();
int num = 0;
list.removeNumber(num);
cerr < "list after removeNumber(" << num << "):\n";
list.printList();
return 0;
}
home