INF205/lab_3/17_and_18/doubly-linked-list.h

65 lines
2.0 KiB
C
Raw Normal View History

2024-03-09 15:44:29 +00:00
#ifndef DOUBLY_LINKED_LIST_H
#define DOUBLY_LINKED_LIST_H
#include <cassert>
2024-03-12 19:52:05 +00:00
#include <cstddef>
2024-03-10 12:42:52 +00:00
#include "queue.h"
2024-03-09 15:44:29 +00:00
namespace seq
{
class DoublyLinkedListNode
{
public:
// return a reference to the stored item
int& get_item() { return this->item; }
// return pointer to next node, or nullptr if this is the final node
DoublyLinkedListNode* get_next() const { return this->next; }
// return pointer to previous node, or nullptr if this is the initial node
DoublyLinkedListNode* get_prev() const { return this->prev; }
// overwrite the item stored in this node
void set_item(int in_item) { this->item = in_item; }
private:
int item = 0;
DoublyLinkedListNode* next = nullptr;
DoublyLinkedListNode* prev = nullptr;
// attach a node behind this node
// if there was a node attached to this previously, it is NOT deleted!
void set_next(DoublyLinkedListNode* in_next) { this->next = in_next; }
// attach a node before this node
// if there was a node attached to this previously, it is NOT deleted!
void set_prev(DoublyLinkedListNode* in_prev) { this->prev = in_prev; }
friend class DoublyLinkedList; // allow DoublyLinkedList to access private members
};
2024-03-10 12:42:52 +00:00
class DoublyLinkedList: public Queue
2024-03-09 15:44:29 +00:00
{
public:
bool empty() const { return (this->head == nullptr); } // test whether the doubly linked list is empty
size_t size() const; // return the size (number of items in the doubly linked list)
2024-03-10 12:42:52 +00:00
void enqueue(int element);
int dequeue();
2024-03-09 15:44:29 +00:00
// return pointer to the head/tail node
DoublyLinkedListNode* begin() const { return this->head; }
DoublyLinkedListNode* end() const { return this->tail; }
2024-03-10 12:42:52 +00:00
void clear() { while(!this->empty()) this->dequeue(); } // remove all the items from the list
2024-03-09 15:44:29 +00:00
~DoublyLinkedList() { this->clear(); }
private:
DoublyLinkedListNode* head = nullptr;
DoublyLinkedListNode* tail = nullptr;
};
}
#endif