Untitled
unknown
plain_text
2 years ago
1.7 kB
5
Indexable
#include "linked_list.h"
// Returns the value at head
int List::head() {
// TODO: Implement this method
if (!m_head) {
throw "Empty List";
}
return m_head->element;
}
// Checks whether the container is empty
bool List::empty() const {
// TODO: Implement this method
if (m_size == 0 || !m_head) {
return true;
}
return false;
}
// Returns the number of elements
size_t List::size() const {
// TODO: Implement this method
return m_size;
}
// Inserts an element to the head
void List::push_head(int element) {
// TODO: Implement this method
Node* newnode = new Node(element);
newnode->next = m_head;
m_head = newnode;
m_size++;
}
// Removes the head element
int List::pop_head() {
// TODO: Implement this method
if (!m_head) {
throw "Empty List";
}
Node* temp = m_head;
m_head = m_head->next;
int popped = temp->element;
delete temp;
m_size--;
return popped;
}
// Checks whether the container contains the specified element
bool List::contains(int element) const {
// TODO: Implement this method
if (!m_head) {
return false;
}
Node* temp = m_head;
while (temp) {
if (temp->element == element) {
return true;
}
temp = temp->next;
}
return false;
}
// Returns a std::string equivalent of the container
std::string List::to_string() const {
// TODO: Implement this method
if (!m_head) {
return "{}";
}
std::string lst1 = "{";
Node* temp = m_head;
while (temp) {
lst1 = lst1 + std::to_string(temp->element);
temp = temp->next;
if (temp) {
lst1 += ", ";
}
}
return lst1 + '}';
}
Editor is loading...
Leave a Comment