I've been getting mixed information from the web.
A quick Google search for what I ask will give many results saying they are separate and operate differently. Enqueue/dequeue for queues and push/pop for stack.
Here for example: Data structures: explanation of pop, push, dequeue, enqueue in this type of exercise
However in reality, push/pop works for both stacks and queues. In stack Push adds to the top of stack while Pop removes from the top of the stack. In queue Push adds to the back of the queue while Pop removes from the front of the queue.
As shown here: https://www.geeksforgeeks.org/queue-cpp-stl/ https://www.geeksforgeeks.org/stack-in-cpp-stl/
So what gives? Theres a difference yes, but why use enqueue/dequeue when push/pop do the same thing? Can push/pop be used interchangably when working with queues or not? I feel like I'm missing something.
Thanks
`
#include <stdio.h>
#include <iostream>
using namespace std;
#include <stack>
#include <queue>
stack<int> CreateStack(int Array[], int length)
{
stack<int> stk;
for (int i = 0; i < length; i++)
{
stk.push(Array[i]);
}
return stk;
}
queue<int> CreateQueue(int Array[], int length)
{
queue<int> que;
for(int i = 0; i < length; i++)
{
que.push(Array[i]);
}
return que;
}
void printStack(stack<int> inputStack)
{
cout << "Top of the stack" << endl;
while(inputStack.empty() == false)
{
cout << inputStack.top() << endl;
inputStack.pop();
}
cout << "Bottom of the stack" << endl;
}
void printQueue(queue<int> inputQueue)
{
cout << "Front of the queue" << endl;
while(inputQueue.empty() == false)
{
cout << inputQueue.front() << endl;
inputQueue.pop();
}
cout << "Back of the queue";
}
int main()
{
int stackArray[] = {2,4,6,8,10};
int arraySize = sizeof(stackArray)/sizeof(stackArray[0]);
stack<int> stk = CreateStack(stackArray, arraySize);
queue<int> que = CreateQueue(stackArray, arraySize);
printStack(stk);
printQueue(que);
}
`
Prints:
Top of the stack
10
8
6
4
2
Bottom of the stack
Front of the queue
2
4
6
8
10
Back of the queue