spz3/List.h

100 lines
1.9 KiB
C++

#ifndef LIST_H
#define LIST_H
template<typename T>
class List {
T *head;
unsigned int num;
public:
explicit List();
[[nodiscard]] T *get_head();
void set_head(T *head);
void insert_head(T *elem);
void insert_tail(T *elem);
void insert_before(T *elem, T *reference_point);
void remove(T *elem);
bool is_empty();
[[nodiscard]] unsigned int get_num() const;
};
template<typename T>
List<T>::List() : head{nullptr}, num{0} {
}
template<typename T>
T *List<T>::get_head() {
return head;
}
template<typename T>
void List<T>::set_head(T *head) {
this->head = head;
}
template<typename T>
void List<T>::insert_head(T *elem) {
if (!head)
elem->next = elem->prev = elem;
else {
elem->next = head;
elem->prev = head->prev;
head->prev->next = elem;
head->prev = elem;
}
this->head = elem;
++num;
}
template<typename T>
void List<T>::insert_tail(T *elem) {
if (!head) {
elem->next = elem->prev = elem;
head = elem;
}
else {
elem->next = head;
elem->prev = head->prev;
head->prev->next = elem;
head->prev = elem;
}
++num;
}
template<typename T>
void List<T>::insert_before(T *elem, T *reference_point) {
elem->next = reference_point;
elem->prev = reference_point->prev;
reference_point->prev = elem;
if (elem->prev == nullptr)
this->head = elem;
else
elem->prev->next = elem;
++num;
}
template<typename T>
void List<T>::remove(T *elem) {
if (elem->next)
elem->next->prev = elem->prev;
if (elem->prev)
elem->prev->next = elem->next;
if (this->head == elem)
this->head = elem->next;
--num;
}
template<typename T>
bool List<T>::is_empty() {
return this->num == 0;
}
template<typename T>
unsigned int List<T>::get_num() const {
return num;
}
#endif //LIST_H