DoublyLinkedListStack

This commit is contained in:
gandc 2024-05-20 04:31:52 +03:00
parent aa166244eb
commit f824162a40
Signed by: gandc
GPG Key ID: 9F77B03D43C42CB4

77
pr6.cpp
View File

@ -7,13 +7,14 @@ template<class T>
class Element {
protected:
Element* next;
Element* prev; // Новый указатель на предыдущий элемент
T info;
public:
Element() : next(nullptr), info(T()) {}
Element(const T& data) : next(nullptr), info(data) {}
Element(Element* Next, const T& data) : next(Next), info(data) {}
Element(const Element& el) : next(el.next), info(el.info) {}
Element() : next(nullptr), prev(nullptr), info(T()) {}
Element(const T& data) : next(nullptr), prev(nullptr), info(data) {}
Element(Element* Next, Element* Prev, const T& data) : next(Next), prev(Prev), info(data) {}
Element(const Element& el) : next(el.next), prev(el.prev), info(el.info) {}
template<class T1>
friend ostream& operator<<(ostream& s, const Element<T1>& el);
@ -26,10 +27,18 @@ public:
return next;
}
Element* getPrev() const { // Новый метод для доступа к prev
return prev;
}
void setNext(Element* nextElement) {
next = nextElement;
}
void setPrev(Element* prevElement) { // Новый метод для установки prev
prev = prevElement;
}
template<class T1> friend class LinkedList;
};
@ -161,18 +170,60 @@ public:
using LinkedList<T>::isEmpty;
};
template<class T>
class DoublyLinkedListStack : public SinglyLinkedListStack<T> {
public:
DoublyLinkedListStack() : SinglyLinkedListStack<T>() {}
virtual Element<T>* push(const T& value) override {
Element<T>* newElement = new Element<T>(value);
if (this->head == nullptr) {
this->head = this->tail = newElement;
}
else {
this->tail->setNext(newElement);
newElement->setPrev(this->tail); // Установка prev для нового элемента
this->tail = newElement;
}
this->count++;
return newElement;
}
virtual Element<T>* pop() override {
if (this->tail == nullptr)
return nullptr;
Element<T>* res = this->tail;
if (this->head == this->tail) {
this->head = this->tail = nullptr;
}
else {
this->tail = this->tail->getPrev();
if (this->tail) {
this->tail->setNext(nullptr); // Удаление ссылки на старый tail
}
}
this->count--;
return res;
}
virtual ~DoublyLinkedListStack() { cout << "\nDoublyLinkedListStack class destructor\n"; }
};
int main() {
StackQueue<int> stackQueue;
DoublyLinkedListStack<int> doublyStack;
// Добавление элементов в конец и начало списка
stackQueue.push_back(1);
stackQueue.push_back(2);
stackQueue.push_front(3);
stackQueue.push_front(4);
// Добавление элементов в стек
doublyStack.push(1);
doublyStack.push(2);
doublyStack.push(3);
doublyStack.push(4);
// Удаление элементов с начала и конца списка
while (!stackQueue.isEmpty()) {
Element<int>* elem = stackQueue.pop_back();
// Удаление элементов из стека
while (!doublyStack.isEmpty()) {
Element<int>* elem = doublyStack.pop();
if (elem) {
cout << elem->getInfo() << " ";
delete elem;