Skip to content

Instantly share code, notes, and snippets.

@commander-trashdin
Last active August 4, 2021 13:44
Show Gist options
  • Select an option

  • Save commander-trashdin/555500cdfdacc89632ababd81c34c0a5 to your computer and use it in GitHub Desktop.

Select an option

Save commander-trashdin/555500cdfdacc89632ababd81c34c0a5 to your computer and use it in GitHub Desktop.
Single linked list
#include <iostream>
#include <memory>
template <class T>
class SLList {
public:
SLList() : size_(0), first_(nullptr) {
}
SLList(std::initializer_list<T> list) : size_(list.size()) {
for (size_t i = list.size() - 1; i-- > 0;) {
auto newnode = std::make_unique<Node>(std::move(list[i]), std::move(first_));
first_ = std::move(newnode);
}
}
void Push(T newdata) {
auto newnode = std::make_unique<Node>(std::move(newdata), std::move(first_));
first_ = std::move(newnode);
size_++;
}
T Pop() {
if (size_ == 0) {
throw std::runtime_error("Cannot pop from an empty list");
}
T data = std::move(first_->data_);
first_ = std::move(first_->tail_);
size_--;
return data;
}
size_t Size() {
return size_;
}
T Head() {
return *first_;
}
T& operator[](size_t index) {
auto node = first_.get();
while (node != nullptr && index != 0) {
node = node->tail_.get();
index--;
}
if (node == nullptr) {
throw std::runtime_error("Index too large");
}
return node->data_;
}
template <class K>
friend void PrintSLList(const SLList<K>& list);
private:
struct Node {
Node(T data, std::unique_ptr<Node> tail) : data_(data), tail_(std::move(tail)) {
}
T data_;
std::unique_ptr<Node> tail_{};
};
size_t size_;
std::unique_ptr<Node> first_;
};
template <class T>
void PrintSLList(const SLList<T>& list) {
auto fst = list.first_.get();
while (fst != nullptr) {
std::cout << fst->data_ << ' ';
fst = fst->tail_.get();
}
}
int main() {
auto list = SLList<int>();
list.Push(1);
list.Push(2);
list.Push(3);
list.Push(4);
PrintSLList(list);
std::cout << list[2] << " ";
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment