inherit a class DoublyLinkedStack

This commit is contained in:
gandc 2024-05-20 12:12:39 +03:00
parent af9ed56a67
commit 5ba267567f
Signed by: gandc
GPG Key ID: 9F77B03D43C42CB4

78
pr6.cpp
View File

@ -161,6 +161,67 @@ public:
using LinkedList<T>::isEmpty;
};
// New class definitions for Doubly Linked List Elements and Doubly Linked Stack
template<class T>
class DoublyLinkedElement : public Element<T> {
protected:
DoublyLinkedElement* prev;
public:
DoublyLinkedElement() : Element<T>(), prev(nullptr) {}
DoublyLinkedElement(const T& data) : Element<T>(data), prev(nullptr) {}
DoublyLinkedElement(DoublyLinkedElement* Next, DoublyLinkedElement* Prev, const T& data)
: Element<T>(Next, data), prev(Prev) {}
DoublyLinkedElement* getPrev() const {
return prev;
}
void setPrev(DoublyLinkedElement* prevElement) {
prev = prevElement;
}
};
template<class T>
class DoublyLinkedStack : public SinglyLinkedListStack<T> {
public:
DoublyLinkedStack() : SinglyLinkedListStack<T>() {}
virtual Element<T>* push(const T& value) override {
DoublyLinkedElement<T>* newElement = new DoublyLinkedElement<T>(value);
if (this->head == nullptr) {
this->head = this->tail = newElement;
}
else {
static_cast<DoublyLinkedElement<T>*>(this->tail)->setNext(newElement);
newElement->setPrev(static_cast<DoublyLinkedElement<T>*>(this->tail));
this->tail = newElement;
}
this->count++;
return newElement;
}
virtual Element<T>* pop() override {
if (this->tail == nullptr)
return nullptr;
DoublyLinkedElement<T>* res = static_cast<DoublyLinkedElement<T>*>(this->tail);
if (this->head == this->tail) {
this->head = this->tail = nullptr;
}
else {
this->tail = res->getPrev();
this->tail->setNext(nullptr);
}
this->count--;
return res;
}
virtual ~DoublyLinkedStack() { cout << "\nDoublyLinkedStack class destructor\n"; }
};
int main() {
StackQueue<int> stackQueue;
@ -180,5 +241,20 @@ int main() {
}
cout << endl;
// Testing DoublyLinkedStack
DoublyLinkedStack<int> doublyLinkedStack;
doublyLinkedStack.push(10);
doublyLinkedStack.push(20);
doublyLinkedStack.push(30);
while (!doublyLinkedStack.isEmpty()) {
Element<int>* elem = doublyLinkedStack.pop();
if (elem) {
cout << elem->getInfo() << " ";
delete elem;
}
}
cout << endl;
return 0;
}
}