override the push() and pop(); overload the << operator for output, and add an indexing operator []
This commit is contained in:
1 file changed
+31
-1
@@ -31,6 +31,7 @@ public:
|
|||||||
}
|
}
|
||||||
|
|
||||||
template<class T1> friend class LinkedList;
|
template<class T1> friend class LinkedList;
|
||||||
|
template<class T1> friend class DoublyLinkedStack;
|
||||||
};
|
};
|
||||||
|
|
||||||
template<class T1>
|
template<class T1>
|
||||||
@@ -212,13 +213,38 @@ public:
|
|||||||
}
|
}
|
||||||
else {
|
else {
|
||||||
this->tail = res->getPrev();
|
this->tail = res->getPrev();
|
||||||
this->tail->setNext(nullptr);
|
if (this->tail) {
|
||||||
|
this->tail->setNext(nullptr);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
this->count--;
|
this->count--;
|
||||||
return res;
|
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"; }
|
virtual ~DoublyLinkedStack() { cout << "\nDoublyLinkedStack class destructor\n"; }
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -247,6 +273,10 @@ int main() {
|
|||||||
doublyLinkedStack.push(20);
|
doublyLinkedStack.push(20);
|
||||||
doublyLinkedStack.push(30);
|
doublyLinkedStack.push(30);
|
||||||
|
|
||||||
|
cout << "Stack contents: " << doublyLinkedStack << endl;
|
||||||
|
|
||||||
|
cout << "Element at index 1: " << doublyLinkedStack[1] << endl;
|
||||||
|
|
||||||
while (!doublyLinkedStack.isEmpty()) {
|
while (!doublyLinkedStack.isEmpty()) {
|
||||||
Element<int>* elem = doublyLinkedStack.pop();
|
Element<int>* elem = doublyLinkedStack.pop();
|
||||||
if (elem) {
|
if (elem) {
|
||||||
|
|||||||
Reference in new issue
Block a user