Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <algorithm>
- #include <cstdlib>
- struct ListNode {
- int value;
- ListNode* prev = nullptr;
- ListNode* next = nullptr;
- };
- class List {
- public:
- List() {
- head_ = nullptr;
- tail_ = nullptr;
- size_ = 0;
- }
- List(const List& other_list) {
- size_ = other_list.size();
- if (other_list.empty()) {
- List();
- return;
- }
- ListNode* node = other_list.head_;
- head_ = new ListNode{node->value};
- ListNode* prev_node = head_;
- while (node != nullptr) {
- ListNode* cur_node = new ListNode{node->value};
- LinkAfter(cur_node, prev_node);
- prev_node = cur_node;
- node = node->next;
- }
- tail_ = prev_node;
- }
- List& operator=(const List& other_list) {
- size_ = other_list.size();
- if (other_list.empty()) {
- head_ = nullptr;
- tail_ = nullptr;
- } else {
- ListNode* node = other_list.head_;
- head_ = new ListNode{node->value};
- ListNode* prev_node = head_;
- while (node->next != nullptr) {
- node = node->next;
- ListNode* cur_node = new ListNode{node->value};
- LinkAfter(cur_node, prev_node);
- prev_node = cur_node;
- }
- tail_ = prev_node;
- }
- return *this;
- }
- bool empty() const {
- return size_ > 0;
- }
- size_t size() const {
- return size_;
- }
- void PushBack(int x) {
- ListNode* new_node = new ListNode{x};
- LinkAfter(new_node, tail_);
- tail_ = new_node;
- }
- void PushFront(int x) {
- ListNode* new_node = new ListNode{x};
- new_node->next = head_->next;
- LinkAfter(head_, new_node);
- head_ = new_node;
- }
- int PopBack() {
- ListNode* copy_tail = tail_;
- Unlink(tail_);
- tail_ = copy_tail->prev;
- return copy_tail->value;
- }
- int PopFront() {
- ListNode* copy_head = head_;
- Unlink(head_);
- head_ = copy_head->next;
- return copy_head->value;
- }
- const int& Back() const {
- return tail_->value;
- }
- int& Back() {
- return tail_->value;
- }
- const int& Front() const {
- return head_->value;
- }
- int& Front() {
- return head_->value;
- }
- private:
- ListNode* head_;
- ListNode* tail_;
- std::size_t size_;
- void Unlink(ListNode* node) {
- ListNode* prev = node->prev;
- ListNode* next = node->next;
- prev->next = next;
- next->prev = prev;
- } // удаляет ноду из списка
- void LinkAfter(ListNode* target, ListNode* after) {
- ListNode* next = after->next;
- target->next = next;
- after->next = target;
- target->prev = after;
- } // добавляет в список элемент after после элемента target
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement