Is this a true Queue? It uses FIFO but it only increments and decrements the “top” variable…not rear. Most queues work from the “rear” of a stack…right?
I originally wrote a stack that worked off a one “int” variable. Now I’m trying to make a queue.
Code:
//----------------------------------------------------------
// Written By: Chad Wood
// Date: 11-13-05
// Description: one int queue
//----------------------------------------------------------
#include <iostream>
#include <stdlib.h>
using namespace std;
const int MAX_ITEMS = 8;
template <class ItemType>
class Queue
{
private:
ItemType stk;
ItemType top;
ItemType rear;
public:
Queue() : stk(0), rear(0), top(-1) {}
void MakeEmpty()
{
stk = 0;
top = -1;
}
bool IsEmpty() const
{
return (top == -1);
}
bool IsFull() const
{
return (top == MAX_ITEMS - 1);
}
void Enqueue(ItemType temp)
{
if (IsFull())
{
cout << "\n Error! Queue is full \n";
return;
}
if (temp >15 || temp < 0)
{
cout << "\nError! Range is not 0-15 \n";
return;
}
stk += temp << (++top * 4);
} //end enqueue
void Dequeue()
{
int temp = 0;
if (IsEmpty())
{
cout << "\n Error! Queue is empty";
return;
}
ItemType print[MAX_ITEMS]; //temp array
for(ItemType i = 0; i < MAX_ITEMS; i++)
print[i] = ( stk >> (i * 4) ) & 0x0F; //place queue on array
ItemType rv = rear;
while(rv < top)
{
print[temp++] = ( stk >> (++rv * 4) ) & 0x0F;
}
stk = 0; //empty queue
for (ItemType i = 0; temp > 0; temp--)
{
// push numbers back on queue
//move each number up one space
stk += print[i++] << (i * 4);
}
top--; //decrement top
} // end dequeue
ItemType Top()
{
if (IsEmpty())
{
cout << "\n Error! Queue is empty";
return 0;
}
ItemType temp = ( stk >> (rear * 4) ) & 0x0F;
return temp;
} // end Top
void PrintStack() const
{
ItemType print;
for (ItemType i = 0; i <= top; i++) //will not print if top = -1
{
print = ( stk >> (i * 4) ) & 0x0F;
cout << print << endl;
}
} //end PrintStack
}; //end class
int main()
{
Queue<int> st;
char i;
while(i != '5')
{
cout << "\n****Press 5 to quit****";
cout << "\n 1 Enqueue | 2 Dequeue | 3 MakeEmpty ";
cin >> i;
cin.ignore();
switch(i)
{
case '1':
{
int num;
cout << "Enter number "; cin >>num;
cin.ignore();
st.Enqueue(num);
st.PrintStack();
break;
}
case '2':
{
st.Dequeue();
st.PrintStack();
break;
}
case '3':
{
st.MakeEmpty();
cout << "\n Queue is empty " <<endl;
break;
}
} // end switch
} // end while loop
system("PAUSE");
return 0;
}