INF205/lab_3/sequences-int/doubly-linked-list.cpp

40 lines
1.2 KiB
C++
Raw Normal View History

2024-03-09 15:44:29 +00:00
#include "doubly-linked-list.h"
using namespace seq;
// return the size (number of items in the doubly linked list)
size_t DoublyLinkedList::size() const
{
size_t count = 0;
for(DoublyLinkedListNode* n = this->head; n != nullptr; n = n->get_next()) count++;
return count;
}
// add an item at the end of the list
2024-03-10 12:42:52 +00:00
void DoublyLinkedList::enqueue(int value)
2024-03-09 15:44:29 +00:00
{
DoublyLinkedListNode* new_node = new DoublyLinkedListNode;
2024-03-10 12:42:52 +00:00
new_node->set_item(value);
2024-03-09 15:44:29 +00:00
if(this->empty()) this->head = new_node;
else
{
this->tail->set_next(new_node);
new_node->set_prev(this->tail); /** attachment in the doubly linked list goes both ways **/
}
this->tail = new_node;
}
// remove the head node and item
2024-03-10 12:42:52 +00:00
int DoublyLinkedList::dequeue()
2024-03-09 15:44:29 +00:00
{
2024-03-10 12:42:52 +00:00
if(this->empty()) return 0; // nothing there to remove
2024-03-09 15:44:29 +00:00
DoublyLinkedListNode* successor = this->head->get_next();
2024-03-10 12:42:52 +00:00
if(successor) successor->set_prev(nullptr); /** we must detach the previous head node from its successor **/
int outgoing = this->head->item;
2024-03-09 15:44:29 +00:00
delete this->head;
this->head = successor; // successor of the previous head is the new head
if(this->head == nullptr) this->tail = nullptr; // catch special case: the list is now empty
2024-03-10 12:42:52 +00:00
return outgoing;
}