Below is the implementation of the DEList class with the functions as per the directions you provided. This includes basic operations such as push, pop from both ends, along with utility functions like checking if the list is empty, obtaining its size, the front and back element along with a toString method.
#include <string>
struct DEItem {
int val;
DEItem* prev;
DEItem* next;
// Constructor
DEItem(int new_val, DEItem* prevItem = nullptr, DEItem* nextItem = nullptr)
: val(new_val), prev(prevItem), next(nextItem) {}
};
class DEList {
public:
// Constructs an empty Double-Ended List
DEList() : head(nullptr), tail(nullptr), Itemcount(0) {}
// Destructor to clean-up memory of current list
~DEList() {
while (head != nullptr) {
DEItem* next = head->next;
delete head;
head = next;
}
}
// Returns a Boolean 'true' if the list is empty
bool empty() const {
return Itemcount == 0;
}
// Returns number of items in the list
int size() const {
return Itemcount;
}
// Returns front item or -1 if empty list
int front() const {
if (empty()) return -1;
return head->val;
}
// Returns back item or -1 if empty list
int back() const {
if (empty()) return -1;
return tail->val;
}
// Adds a new integer to the front of the list
void push_front(int new_val) {
DEItem* newItem = new DEItem(new_val, nullptr, head);
if (empty()) {
head = tail = newItem;
} else {
head->prev = newItem;
head = newItem;
}
Itemcount++;
}
// Adds a new integer to the back of the list
void push_back(int new_val) {
DEItem* newItem = new DEItem(new_val, tail, nullptr);
if (empty()) {
head = tail = newItem;
} else {
tail->next = newItem;
tail = newItem;
}
Itemcount++;
}
// Removes the front item of the list (if it exists)
void pop_front() {
if (!empty()) {
DEItem* oldHead = head;
head = head->next;
if (head != nullptr) {
head->prev = nullptr;
} else { // List becomes empty
tail = nullptr;
}
delete oldHead;
Itemcount--;
}
}
// Removes the back item of the list (if it exists)
void pop_back() {
if (!empty()) {
DEItem* oldTail = tail;
tail = tail->prev;
if (tail != nullptr) {
tail->next = nullptr;
} else { // List becomes empty
head = nullptr;
}
delete oldTail;
Itemcount--;
}
}
// Converts the contents of the list to a string with spaces between
std::string conv_to_string() const {
std::string result;
DEItem* current = head;
while (current != nullptr) {
result += std::to_string(current->val);
if (current->next != nullptr) {
result += " ";
}
current = current->next;
}
return result;
}
private:
DEItem* head;
DEItem* tail;
int Itemcount; // Maintains a count of items for easy size() implementation
};
This ELList class provides you with a doubly linked list implementation that supports adding and removing elements from both ends, as well as retrieving the first and last element. The conv_to_string method allows you to easily print the contents of the list for debugging or other purposes.