Skip to content

Instantly share code, notes, and snippets.

@ParticleG
Created September 6, 2023 14:53
Show Gist options
  • Save ParticleG/5a83732140848c8ca4dcc0a3ecc3bcb6 to your computer and use it in GitHub Desktop.
Save ParticleG/5a83732140848c8ca4dcc0a3ecc3bcb6 to your computer and use it in GitHub Desktop.
//
// Created by g29624 on 2022/12/7.
//
#pragma once
#include <iostream>
#include <memory>
template<typename T>
class SmartList {
public:
class SmartNode {
public:
explicit SmartNode(T data) : data{data}, next{nullptr} {}
T data;
std::unique_ptr<SmartNode> next;
};
public:
SmartList() : _head{nullptr} {}
SmartList(const SmartList &smartList) {
SmartNode *root = smartList._head.get();
std::unique_ptr<SmartNode> newHead{nullptr};
SmartNode *newHeadPtr{nullptr};
while (root) {
auto temp{std::make_unique<SmartNode>(root->data)};
if (newHead == nullptr) {
newHead = std::move(temp);
newHeadPtr = newHead.get();
} else {
newHeadPtr->next = std::move(temp);
newHeadPtr = newHeadPtr->next.get();
}
root = root->next.get();
}
_head = std::move(newHead);
}
SmartList(SmartList &&smartList) noexcept {
_head = std::move(smartList._head);
}
SmartList &operator=(const SmartList &smartList) {
this->SmartList(smartList);
return *this;
}
SmartList &operator=(SmartList &&smartList) noexcept {
this->SmartList(std::move(smartList));
return *this;
}
void push(T data) {
auto temp{std::make_unique<SmartNode>(data)};
if (_head) {
temp->next = std::move(_head);
_head = std::move(temp);
} else {
_head = std::move(temp);
}
}
void pop() {
if (_head == nullptr) {
return;
}
std::unique_ptr<SmartNode> temp = std::move(_head);
_head = std::move(temp->next);
}
void clean() {
while (_head) {
_head = std::move(_head->next);
}
}
void reverse() {
SmartList tmp;
SmartNode *root = _head.get();
while (root) {
tmp.push(root->data);
root = root->next.get();
}
clean();
_head = std::move(tmp._head);
}
~SmartList() {
clean();
}
friend std::ostream &operator<<(std::ostream &os, const SmartList &list) {
auto head = list._head.get();
while (head) {
os << head->data << ' ';
head = head->next.get();
}
return os;
}
private:
std::unique_ptr<SmartNode> _head;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment