INF205/lab_3/17_and_18/singly-linked-list.cpp

33 lines
966 B
C++
Raw Normal View History

2024-03-12 19:52:05 +00:00
#include <cstddef>
2024-03-09 15:44:29 +00:00
#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;
}
2024-03-10 12:16:20 +00:00
void SinglyLinkedList::enqueue(int value)
2024-03-09 15:44:29 +00:00
{
SinglyLinkedListNode* new_node = new SinglyLinkedListNode;
2024-03-10 12:16:20 +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);
this->tail = new_node;
}
2024-03-10 12:16:20 +00:00
int SinglyLinkedList::dequeue()
2024-03-09 15:44:29 +00:00
{
2024-03-10 12:16:20 +00:00
if(this->empty()) return 0; // nothing there to remove
2024-03-09 15:44:29 +00:00
SinglyLinkedListNode* successor = this->head->get_next();
2024-03-10 12:42:52 +00:00
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;
2024-03-10 12:16:20 +00:00
}