This commit is contained in:
lda committed 2025-06-30 09:44:58 +07:00
1 parent febea5cd30
commit af1b471799
1 file changed
+23 -23
+23 -23
View File
@@ -5,18 +5,18 @@
struct Node struct Node
{ {
int data; int data;
Node *prev; std::weak_ptr<Node> prev;
std::unique_ptr<Node> next; std::shared_ptr<Node> next;
Node(int value) : data(value), prev(nullptr), next(nullptr) {} Node(int value) : data(value), prev(), next(nullptr) {}
}; };
// Doubly linked list class // Doubly linked list class
class DoublyLinkedList class DoublyLinkedList
{ {
private: private:
std::unique_ptr<Node> head; std::shared_ptr<Node> head;
Node *tail; std::shared_ptr<Node> tail;
int size; int size;
public: public:
@@ -25,17 +25,17 @@ public:
// Adds a value to the front of the list (O(1)) // Adds a value to the front of the list (O(1))
void push_front(int value) void push_front(int value)
{ {
auto new_node = std::make_unique<Node>(value); auto new_node = std::make_shared<Node>(value);
if (!head) if (!head)
{ {
head = std::move(new_node); head = new_node;
tail = head.get(); tail = new_node;
} }
else else
{ {
new_node->next = std::move(head); new_node->next = head;
head->prev = new_node.get(); head->prev = new_node;
head = std::move(new_node); head = new_node;
} }
size++; size++;
} }
@@ -43,17 +43,17 @@ public:
// Adds a value to the end of the list (O(1)) // Adds a value to the end of the list (O(1))
void push_back(int value) void push_back(int value)
{ {
auto new_node = std::make_unique<Node>(value); auto new_node = std::make_shared<Node>(value);
if (!tail) if (!tail)
{ {
head = std::move(new_node); head = new_node;
tail = head.get(); tail = new_node;
} }
else else
{ {
tail->next = std::move(new_node); tail->next = new_node;
tail->next->prev = tail; new_node->prev = tail;
tail = tail->next.get(); tail = new_node;
} }
size++; size++;
} }
@@ -66,14 +66,14 @@ public:
throw std::runtime_error("List is empty"); throw std::runtime_error("List is empty");
} }
int value = head->data; int value = head->data;
head = std::move(head->next); head = head->next;
if (head) if (head)
{ {
head->prev = nullptr; head->prev.reset();
} }
else else
{ {
tail = nullptr; tail.reset();
} }
size--; size--;
return value; return value;
@@ -87,7 +87,7 @@ public:
throw std::runtime_error("List is empty"); throw std::runtime_error("List is empty");
} }
int value = tail->data; int value = tail->data;
tail = tail->prev; tail = tail->prev.lock();
if (tail) if (tail)
{ {
tail->next.reset(); tail->next.reset();
@@ -103,11 +103,11 @@ public:
// Prints the list from front to back (O(n)) // Prints the list from front to back (O(n))
void print() const void print() const
{ {
Node *current = head.get(); auto current = head;
while (current) while (current)
{ {
std::cout << current->data << " "; std::cout << current->data << " ";
current = current->next.get(); current = current->next;
} }
std::cout << std::endl; std::cout << std::endl;
} }