Last active
August 30, 2018 22:01
-
-
Save alexnoz/5b4b7356c18c559c6c08dabdc4d5b9b7 to your computer and use it in GitHub Desktop.
A linked list implementation written in C++
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
#include <iostream> | |
#include <stdexcept> | |
#include <functional> | |
struct Node { | |
int data; | |
Node *next; | |
}; | |
using fn = std::function<void(Node*)>; | |
class LinkedList { | |
private: | |
Node *head; | |
Node* getNodeAt(int pos) { | |
Node *cur = head; | |
int i = 2; | |
for (; i < pos && cur->next; i++) | |
cur = cur->next; | |
if (i != pos) | |
throw std::out_of_range("Index is out of bounds"); | |
return cur; | |
} | |
public: | |
LinkedList(): head(nullptr) {} | |
~LinkedList() { | |
Node *cur = head; | |
while (cur) { | |
Node *temp = cur->next; | |
delete cur; | |
cur = temp; | |
} | |
delete head; | |
} | |
void prepend(int data) { | |
Node *newNode = new Node { data, head }; | |
head = newNode; | |
} | |
void append(int data) { | |
Node *newNode = new Node { data, nullptr }; | |
if (!head) { | |
head = newNode; | |
return; | |
} | |
Node *cur = head; | |
while (cur->next) | |
cur = cur->next; | |
cur->next = newNode; | |
} | |
void insertAt(int pos, int data) { | |
if (pos == 1) prepend(data); | |
Node *cur = getNodeAt(pos); | |
Node *newNode = new Node { data, cur->next }; | |
cur->next = newNode; | |
} | |
void removeAt(int pos) { | |
Node *toRemove; | |
if (pos == 1) { | |
toRemove = head; | |
head = head->next; | |
delete toRemove; | |
return; | |
} | |
Node *cur = getNodeAt(pos); | |
toRemove = cur->next; | |
cur->next = cur->next->next; | |
delete toRemove; | |
} | |
void reverse() { | |
Node *cur = head, *prev = nullptr; | |
while (cur) { | |
Node *next = cur->next; | |
cur->next = prev; | |
prev = cur; | |
cur = next; | |
} | |
head = prev; | |
} | |
void reverseRecursive() { | |
fn reverseR = [&](Node *cur) { | |
if (!cur->next) { | |
head = cur; | |
return; | |
} | |
reverseR(cur->next); | |
Node *prev = cur->next; | |
prev->next = cur; | |
cur->next = nullptr; | |
}; | |
reverseR(head); | |
} | |
friend std::ostream& operator<<(std::ostream&, const LinkedList&); | |
}; | |
std::ostream& operator<<(std::ostream& out, const LinkedList& ls) { | |
Node* cur = ls.head; | |
while (cur) { | |
out << cur->data << ' '; | |
cur = cur->next; | |
} | |
out << '\n'; | |
return out; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment