In data structures, stacks and queues are fundamental concepts. They are both linear data structures that store and organize data in a specific way.
A stack is an abstract data type that follows the LIFO (Last In, First Out) principle. Think of it as a stack of books where you can only access the top book. You can only add or remove elements from the top of the stack. This means that the last element that is added will be the first one to be removed. Some common operations on a stack include:
push
: Add an element to the top of the stack.pop
: Remove the top element from the stack.top
: Retrieve the top element of the stack without removing it.
Here is an example of using a stack in C++:
1#include <iostream>
2#include <stack>
3
4int main() {
5 std::stack<int> myStack;
6 myStack.push(1);
7 myStack.push(2);
8 myStack.push(3);
9
10 std::cout << "Top element of the stack: " << myStack.top() << std::endl;
11
12 myStack.pop();
13
14 std::cout << "Stack after popping: ";
15 while (!myStack.empty()) {
16 std::cout << myStack.top() << " ";
17 myStack.pop();
18 }
19 std::cout << std::endl;
20
21 return 0;
22}
A queue is another abstract data type that follows the FIFO (First In, First Out) principle. Think of it like a line of people waiting for a bus. The person who arrives first is the first one to board the bus, while the person who arrives last will board the bus last. Some common operations on a queue include:
enqueue
: Add an element to the end of the queue.dequeue
: Remove the first element from the queue.front
: Retrieve the first element of the queue without removing it.
Here is an example of using a queue in C++:
1#include <iostream>
2#include <queue>
3
4int main() {
5 std::queue<int> myQueue;
6 myQueue.push(1);
7 myQueue.push(2);
8 myQueue.push(3);
9
10 std::cout << "Front element of the queue: " << myQueue.front() << std::endl;
11
12 myQueue.pop();
13
14 std::cout << "Queue after dequeuing: ";
15 while (!myQueue.empty()) {
16 std::cout << myQueue.front() << " ";
17 myQueue.pop();
18 }
19 std::cout << std::endl;
20
21 return 0;
22}
xxxxxxxxxx
}
int main() {
std::stack<int> myStack;
myStack.push(1);
myStack.push(2);
myStack.push(3);
std::cout << "Top element of the stack: " << myStack.top() << std::endl;
myStack.pop();
std::cout << "Stack after popping: ";
while (!myStack.empty()) {
std::cout << myStack.top() << " ";
myStack.pop();
}
std::cout << std::endl;
std::queue<int> myQueue;
myQueue.push(1);
myQueue.push(2);
myQueue.push(3);
std::cout << "Front element of the queue: " << myQueue.front() << std::endl;
myQueue.pop();