Skip to content

Instantly share code, notes, and snippets.

@RaphGL
Created May 16, 2024 23:43
Show Gist options
  • Save RaphGL/c47b2876435dd340e34e77cf368faf00 to your computer and use it in GitHub Desktop.
Save RaphGL/c47b2876435dd340e34e77cf368faf00 to your computer and use it in GitHub Desktop.
A linked list in C++ cause reasons???
#include <cstddef>
#include <initializer_list>
#include <iostream>
#include <stdexcept>
template <typename T> struct LLNode {
T val{};
LLNode<T> *next{nullptr};
};
template <typename T> class LinkedList {
std::size_t m_len{0};
LLNode<T> *m_head{nullptr};
public:
LinkedList(T val) {
m_head = new LLNode<T>;
m_head->val = val;
++m_len;
}
LinkedList(std::initializer_list<T> vals) {
m_head = new LLNode<T>;
auto n = m_head;
std::size_t i = 0;
for (const auto val : vals) {
n->val = val;
if (i < std::size(vals) - 1) {
n->next = new LLNode<T>;
n = n->next;
}
++i;
}
m_len = i;
}
std::size_t len() const { return m_len; }
T at(std::size_t i) {
if (i >= m_len) {
throw std::out_of_range("index out of range");
}
std::size_t j = 0;
for (auto n = m_head; n != nullptr; n = n->next) {
if (j == i) {
return n->val;
}
++j;
}
return {};
}
T operator[](std::size_t i) {
return at(i);
}
void push_back(T val) {
auto n = m_head;
for (; n->next != nullptr; n = n->next) {
}
n->next = new LLNode<T>;
n->next->val = val;
++m_len;
}
void push_front(T val) {
auto prev_head = m_head;
m_head = new LLNode<T>;
m_head->next = prev_head;
m_head->val = val;
++m_len;
}
T pop_back() {
auto n = m_head;
for (; n->next->next != nullptr; n = n->next) {
}
auto next = n->next;
n->next = nullptr;
auto val = next->val;
delete next;
--m_len;
return val;
}
T pop_front() {
T val = m_head->val;
auto prev_head = m_head;
m_head = m_head->next;
delete prev_head;
--m_len;
return val;
}
friend std::ostream &operator<<(std::ostream &out, LinkedList<T> list) {
out << '[';
for (auto n = list.m_head; n != nullptr; n = n->next) {
out << n->val << ' ';
}
out << "\b]";
return out;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment