Stack and Queue in C++
Queue
- Operations:
push(),pop(),empty(),front(),back()
Stack
- Operations:
push(),pop(),empty(),top()
Key Difference:
- Queue → FIFO (First In First Out)
- Stack → LIFO (Last In First Out)
Queue & Stack Initialization
Section titled “Queue & Stack Initialization”Queue Initialization & Access
queue<int> myQue; // Initialize empty for(int i = 1; i <= 3; i++) myQue.push(i); // Push in loop- ❌
queue<int> myQue = {1, 2, 3};⭐ not allowed - ✅
queue<int> myQue({1, 2, 3});⭐ // using constructor
Stack Initialization & Access
stack<int> mySt; // Initialize empty for(int i = 1; i <= 3; i++) mySt.push(i); // Push in loop- ❌
stack<int> mySt = {1, 2, 3};→ not allowed - ✅
stack<int> mySt({1, 2, 3});→ works using constructor (rarely used)
Queue vs Stack Operations
Queue (FIFO)
- ✅
myQue.size()→ number of elements - ❌
myQue[0]→ direct indexing not allowed - ✅
myQue.front()→ access first element - ✅
myQue.back()→ access last element - ✅
myQue.push(x)→ add element at back - ✅
myQue.pop()→ remove element from front
Stack (LIFO)
- ✅
mySt.size()→ number of elements - ❌
mySt[0]→ direct indexing not allowed - ✅
mySt.top()→ access top element - ✅
mySt.push(x)→ add element at top - ✅
mySt.pop()→ remove top element
Stack #include <stack>
std::stack<int> s;
// Push elements onto the stacks.push(1);s.push(2);s.push(3);
// Display the top elementstd::cout << "Top element: " << s.top() << std::endl;
// Pop the top elements.pop();
// Display the new top elementstd::cout << "New top element: " << s.top() << std::endl;
// Check if the stack is emptyif (s.empty()) { std::cout << "Stack is empty" << std::endl;} else { std::cout << "Stack size: " << s.size() << std::endl;}Queue #include <queue>
std::queue<int> q;
// Push elements into the queueq.push(1);q.push(2);q.push(3);
// Display the front elementstd::cout << "Front element: " << q.front() << std::endl;
// Pop the front elementq.pop();
// Display the new front elementstd::cout << "New front element: " << q.front() << std::endl;
// Check if the queue is emptyif (q.empty()) { std::cout << "Queue is empty" << std::endl;} else { std::cout << "Queue size: " << q.size() << std::endl;}Additional Notes
- Both
std::stackandstd::queueare container adapters that use other underlying containers (likestd::dequeorstd::list) to store elements. -By default,std::stackusesstd::deque, andstd::queuealso usesstd::deque. You can change the underlying container if needed.