override the push() and pop(); overload the << operator for output, and add an indexing operator []
This commit is contained in:
parent
5ba267567f
commit
ae743ee8ec
32
pr6.cpp
32
pr6.cpp
@ -31,6 +31,7 @@ public:
|
||||
}
|
||||
|
||||
template<class T1> friend class LinkedList;
|
||||
template<class T1> friend class DoublyLinkedStack;
|
||||
};
|
||||
|
||||
template<class T1>
|
||||
@ -212,13 +213,38 @@ public:
|
||||
}
|
||||
else {
|
||||
this->tail = res->getPrev();
|
||||
this->tail->setNext(nullptr);
|
||||
if (this->tail) {
|
||||
this->tail->setNext(nullptr);
|
||||
}
|
||||
}
|
||||
|
||||
this->count--;
|
||||
return res;
|
||||
}
|
||||
|
||||
// Overload the << operator for output
|
||||
friend ostream& operator<<(ostream& os, const DoublyLinkedStack& stack) {
|
||||
DoublyLinkedElement<T>* current = static_cast<DoublyLinkedElement<T>*>(stack.head);
|
||||
while (current != nullptr) {
|
||||
os << current->getInfo() << " ";
|
||||
current = static_cast<DoublyLinkedElement<T>*>(current->getNext());
|
||||
}
|
||||
return os;
|
||||
}
|
||||
|
||||
// Overload the [] operator for indexing
|
||||
T& operator[](int index) {
|
||||
if (index < 0 || index >= this->count) {
|
||||
throw out_of_range("Index out of range");
|
||||
}
|
||||
|
||||
DoublyLinkedElement<T>* current = static_cast<DoublyLinkedElement<T>*>(this->head);
|
||||
for (int i = 0; i < index; ++i) {
|
||||
current = static_cast<DoublyLinkedElement<T>*>(current->getNext());
|
||||
}
|
||||
return current->info;
|
||||
}
|
||||
|
||||
virtual ~DoublyLinkedStack() { cout << "\nDoublyLinkedStack class destructor\n"; }
|
||||
};
|
||||
|
||||
@ -247,6 +273,10 @@ int main() {
|
||||
doublyLinkedStack.push(20);
|
||||
doublyLinkedStack.push(30);
|
||||
|
||||
cout << "Stack contents: " << doublyLinkedStack << endl;
|
||||
|
||||
cout << "Element at index 1: " << doublyLinkedStack[1] << endl;
|
||||
|
||||
while (!doublyLinkedStack.isEmpty()) {
|
||||
Element<int>* elem = doublyLinkedStack.pop();
|
||||
if (elem) {
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user