2024-03-09 15:44:29 +00:00
|
|
|
#ifndef SINGLY_LINKED_LIST_H
|
|
|
|
#define SINGLY_LINKED_LIST_H
|
|
|
|
|
|
|
|
#include <cassert>
|
2024-03-10 12:16:20 +00:00
|
|
|
#include "queue.h"
|
2024-03-09 15:44:29 +00:00
|
|
|
|
|
|
|
namespace seq
|
|
|
|
{
|
|
|
|
class SinglyLinkedListNode
|
|
|
|
{
|
|
|
|
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
|
|
|
|
SinglyLinkedListNode* get_next() const { return this->next; }
|
|
|
|
|
|
|
|
// overwrite the item stored in this node
|
|
|
|
void set_item(int in_item) { this->item = in_item; }
|
|
|
|
|
|
|
|
private:
|
|
|
|
int item = 0;
|
|
|
|
SinglyLinkedListNode* next = nullptr;
|
|
|
|
|
|
|
|
// attach a node to this node
|
|
|
|
// if there was a node attached to this previously, it is NOT deleted!
|
|
|
|
void set_next(SinglyLinkedListNode* in_next) { this->next = in_next; }
|
|
|
|
|
|
|
|
friend class SinglyLinkedList; // allow SinglyLinkedList to access private members
|
|
|
|
};
|
|
|
|
|
2024-03-10 12:16:20 +00:00
|
|
|
class SinglyLinkedList: public Queue
|
2024-03-09 15:44:29 +00:00
|
|
|
{
|
|
|
|
public:
|
|
|
|
bool empty() const { return (this->head == nullptr); } // test whether the singly linked list is empty
|
|
|
|
size_t size() const; // return the size (number of items in the singly linked list)
|
|
|
|
|
2024-03-12 19:52:05 +00:00
|
|
|
void enqueue(int value);
|
2024-03-10 12:16:20 +00:00
|
|
|
int dequeue();
|
2024-03-09 15:44:29 +00:00
|
|
|
|
2024-03-10 12:16:20 +00:00
|
|
|
void clear() { while(!this->empty()) this->dequeue(); } // remove all the items from the list
|
2024-03-09 15:44:29 +00:00
|
|
|
~SinglyLinkedList() { this->clear(); }
|
|
|
|
|
|
|
|
private:
|
|
|
|
SinglyLinkedListNode* head = nullptr;
|
|
|
|
SinglyLinkedListNode* tail = nullptr;
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
|
|
|
#endif
|