INF205/lab_3/17_and_18/singly-linked-list.cpp
2024-03-12 20:52:56 +01:00

33 lines
966 B
C++

#include <cstddef>
#include "singly-linked-list.h"
using namespace seq;
// return the size (number of items in the singly linked list)
size_t SinglyLinkedList::size() const
{
size_t count = 0;
for(SinglyLinkedListNode* n = this->head; n != nullptr; n = n->get_next()) count++;
return count;
}
void SinglyLinkedList::enqueue(int value)
{
SinglyLinkedListNode* new_node = new SinglyLinkedListNode;
new_node->set_item(value);
if(this->empty()) this->head = new_node;
else this->tail->set_next(new_node);
this->tail = new_node;
}
int SinglyLinkedList::dequeue()
{
if(this->empty()) return 0; // nothing there to remove
SinglyLinkedListNode* successor = this->head->get_next();
int outgoing = this->head->item;
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
return outgoing;
}