2.
Stacks
In C++, a stack can be implemented using the Standard Template Library (STL) stack
container, which follows the LIFO principle.
Example:
cpp
#include <iostream>
#include <stack> // Required for usingstack
using namespcace std;
// This line tells the compiler to use the `std` namespace for
all standard library elements.
// This avoids having to write `std::` before every standard
library component we use.
using namespace std;
int main() {
// Create a stack to store integers
stack<int> myStack;
// Push elements onto the stack
myStack.push(10);
myStack.push(20);
myStack.push(30);
// Get the top element without removing it
int topElement = myStack.top();
cout << "Top element: " << topElement << endl;
// Remove the top element from the stack
myStack.pop();
cout << "Top element removed." << endl;
// Display the remaining elements in the stack (if any)
cout << "Stack contents after pop: ";
while (!myStack.empty()) {
cout << myStack.top() << " "; // Get the current top
element
myStack.pop(); // Remove the top element
}
return 0;
}
Key Operations:
● push(): Add an element to the top of the stack.
● pop(): Remove the top element.
● top(): View the top element without removing it.
3. Queues
In C++, a queue can be implemented using the STL queue container, which follows the
FIFO principle.
Example:
cpp
#include <iostream>
#include <queue> // Required for using std::queue
using namespace std;
int main() {
// Create a queue to store integers
queue<int> myQueue;
// Enqueue elements to the queue
myQueue.push(10);
myQueue.push(20);
myQueue.push(30);
// Get the front element without removing it
int frontElement = myQueue.front();
cout << "Front element: " << frontElement << endl;
// Remove the front element from the queue
myQueue.pop();
cout << "Front element removed." << endl;
// Display the remaining elements in the queue (if any)
cout << "Queue contents after dequeue: ";
while (!myQueue.empty()) {
cout << myQueue.front() << " "; // Get the front element
myQueue.pop(); // Remove the front element
}
return 0;
}
Key Operations:
● push(): Add an element to the rear of the queue (enqueue).
● pop(): Remove the front element (dequeue).
● front(): View the front element without removing it.